/**
 * Created by apple on 16/7/4.
 */
angular.module('starter.taskController', ['starter.taskService', 'starter.taskDirective', 'task.qutyChangeController', 'task.commonChoicePhotoController'])
    .controller('DeliveryCtrl', function ($rootScope, $loading, $cordovaDialogs, $ionicHistory, $scope, $stateParams, $dfHttp, $user, $timeout, $state, $lookup, $cordovaBarcodeScanner, $log) {


        //获取当前项目信息
        $scope.project = $stateParams.args;
        //获取当前用户信息
        $scope.user = $user.getCurrentUserSync();

        $scope.errorIndex = 0;

        //收货清单
        $scope.receivingData = {
            userId: "",
            dataList: []
        };

        // modulesNum
        $scope.vm = { modulesNum: 0 };

        //收货清单分类
        $scope.receivingDataForCategory = {
            "GFZJ": [],
            "PDX": [],
            "OTHER": []
        };

        // 扫码清单
        $scope.serialNumber = {
            userId: "",
            serialList: []
        };

        // 扫码清单分类
        $scope.serialNumberForCategory = {
            "GFZJ": [],
            "NBQ": []
        };

        $scope.receivingDataForGFZJLength = 0;
        $scope.theFirstElementOfGFZJ = {};

        $scope.goChoice = function (type, current, index) {
            $scope.choiceNBQIndex = index;
            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current
                }
            });
        };

        $timeout(function () {
            getReceAndSerData($scope.user.userId, $scope.project.projectId);
            //获取收货数据清单
            // getReceivingData($scope.user.userId, $scope.project.projectId);
            //
            // 获取扫码清单
            // getSerialNumber($scope.user.userId, $scope.project.projectId);
        }, 300);

        $scope.solarModuleListHidden = false;
        $scope.inverterModuleListHidden = false;
        $scope.communicationListHidden = false;

        $scope.switchSolarModuleList = function () {
            $scope.solarModuleListHidden = !$scope.solarModuleListHidden;
            // if ($scope.solarModuleListHidden) {
            //   document.getElementById("solarModuleList").setAttribute("class","list list-delivery list-hidden");
            // } else {
            //   document.getElementById("solarModuleList").setAttribute("class","list list-delivery");
            // }
        };
        $scope.switchInverterModuleList = function () {
            $scope.inverterModuleListHidden = !$scope.inverterModuleListHidden;
        };
        $scope.switchCommunicationList = function () {
            $scope.communicationListHidden = !$scope.communicationListHidden;
        };

        /**
         * 获取清单
         * @param userId
         * @param projectId
         */
        function getReceAndSerData(userId, projectId) {
            $loading.show("获取数据中...");
            $dfHttp.get("api/others/getReceAndSerData.json", {
                userId: userId,
                projectId: projectId
            }).success(function (data) {
                if (data.code == "SUCCESS") {
                    $scope.vm.modulesNum = data.data.modulesNum;
                    $loading.hide();
                    // 收货数据
                    angular.forEach(data.data.dataList, function (d, i) {
                        //判断产品编码
                        if (d.categoryCode == "A0101") { //太阳能组件
                            $scope.receivingDataForCategory.GFZJ.push(d);
                        } else if (d.categoryCode == "A0303") { //交流配电箱
                            $scope.receivingDataForCategory.PDX.push(d);
                        } else { //支架系统
                            if (d.categoryCode != "A030408") {
                                $scope.receivingDataForCategory.OTHER.push(d);
                            }
                        }
                    })

                    // 扫码数据
                    angular.forEach(data.data.serialList, function (d, i) {
                        if (d.categoryCode == "A0101") { //光伏组件
                            $scope.serialNumberForCategory.GFZJ.push(d);
                        }

                        if (d.categoryCode == "A0302") { // 逆变器
                            $lookup.getWithLookupCode(d.itemRealCode).executeSuccess(function (lookup) {
                                d.itemMeaning = lookup.lookupMeaning;
                            });
                            $scope.serialNumberForCategory.NBQ.push(d);
                        }
                    })

                    $scope.receivingDataForGFZJLength = $scope.receivingDataForCategory.GFZJ.length;
                    $scope.theFirstElementOfGFZJ = $scope.receivingDataForCategory.GFZJ[0];
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (e) {
                $loading.showError("网络异常,请稍后再试");
            });
        }

        // /**
        //  * 获取扫码清单
        //  * @param userId
        //  * @param projectId
        //  */
        // function getSerialNumber(userId, projectId) {
        //   $dfHttp.get("api/others/getSerialNumber.json", {
        //     "userId": userId,
        //     "projectId": projectId
        //     // "projectId": 1000
        //   }).success(function (data) {
        //     console.log(data);
        //     if (data.code == "SUCCESS") {
        //       angular.forEach(data.data.serialList, function (d, i) {
        //         if (d.categoryCode == "A0101") { //光伏组件
        //           $scope.serialNumberForCategory.GFZJ.push(d);
        //         }
        //
        //         if (d.categoryCode == "A0302") { // 逆变器
        //           $lookup.getWithLookupCode(d.itemRealCode).executeSuccess(function (lookup) {
        //             d.itemMeaning = lookup.lookupMeaning;
        //           });
        //           $scope.serialNumberForCategory.NBQ.push(d);
        //         }
        //       })
        //     } else {
        //       $loading.showError("网络出了一点小问题,请稍后再试");
        //     }
        //   }).error(function (e) {
        //     $loading.showError("网络异常,请稍后再试");
        //   });
        // }
        //
        // /**
        //  * 获取收货数据清单
        //  * @param userId
        //  * @param projectId
        //  */
        // function getReceivingData(userId, projectId) {
        //   $dfHttp.get("api/others/getReceivingData.json", {
        //     "userId": userId,
        //     "projectId": projectId
        //     // "projectId": 1000
        //   }).success(function (data) {
        //     if (data.code == "SUCCESS") {
        //       angular.forEach(data.data.dataList, function (d, i) {
        //         //判断产品编码
        //         if (d.categoryCode == "A0101") { //太阳能组件
        //           $scope.receivingDataForCategory.GFZJ.push(d);
        //         } else if (d.categoryCode == "A0303") { //交流配电箱
        //           $scope.receivingDataForCategory.PDX.push(d);
        //         } else{ //支架系统
        //           if (d.categoryCode != "A030408"){
        //             $scope.receivingDataForCategory.OTHER.push(d);
        //           }
        //         }
        //       })
        //
        //       $scope.receivingDataForGFZJLength = $scope.receivingDataForCategory.GFZJ.length;
        //       $scope.theFirstElementOfGFZJ = $scope.receivingDataForCategory.GFZJ[0];
        //     } else {
        //       $loading.showError("网络出了一点小问题,请稍后再试");
        //     }
        //   }).error(function (e) {
        //     $loading.showError("网络异常,请稍后再试");
        //   })
        // }

        /**
         * 全到
         * @param title
         */
        $scope.all = function (title) {
            //配电箱
            if (title == "PDX") {
                angular.forEach($scope.receivingDataForCategory.PDX, function (d, i) {
                    d.receivedQty = d.itemQty;
                })
            }

            //支架系统
            if (title == "OTHERS") {
                angular.forEach($scope.receivingDataForCategory.OTHER, function (d, i) {
                    d.receivedQty = d.itemQty;
                })
            }
        }

        // 收货列表监听
        $scope.$watch("receivingDataForCategory.OTHER", function () {
            angular.forEach($scope.receivingDataForCategory.OTHER, function (d, i) {
                if (d.itemQty < d.receivedQty) {
                    d.receivedQty = d.itemQty;
                }
            })
        }, true);
        $scope.$watch("receivingDataForCategory.PDX", function () {
            angular.forEach($scope.receivingDataForCategory.PDX, function (d, i) {
                if (d.itemQty < d.receivedQty) {
                    d.receivedQty = d.itemQty;
                }
            })
        }, true);

        $scope.$on('$stateChangeSuccess', function () {
            var item = $lookup.getChoiceItem();

            if (item) {
                angular.forEach($scope.serialNumberForCategory.NBQ, function (d, i) {
                    if (i == $scope.choiceNBQIndex) {
                        if (d.itemCode == item.type) {
                            d.itemRealCode = item.code;
                            d.itemMeaning = item.meaning;
                        }
                    }
                })
            }
        });

        /**
         * 保存
         */
        $scope.save = function () {
            var receivingData = getReceivingDataList($scope.receivingDataForCategory);
            var serialNumber = getSerialNumberList($scope.serialNumberForCategory);

            if ($scope.serialNumberForCategory.NBQ.length == 0 || $scope.errorIndex == 0) {
                saveSerialAndRecData(receivingData, serialNumber, $scope.user.userId);
            } else {
                $scope.errorIndex = 0;
                $loading.showError("sim不能为空");
            }
        }

        function checkError(obj, index) {
            if (angular.isUndefined(obj.sim1) || obj.sim1.length == 0) {
                if (angular.isUndefined(obj.sim2) || obj.sim2.length == 0) {
                    $scope.errorIndex = $scope.errorIndex + 1;
                }
            }
        }

        /**
         * 保存扫码清单数据
         * @param serialNumber
         */
        function saveSerialNumber(serialNumber) {
            $loading.show("正在保存扫码清单...");
            serialNumber.userId = $scope.user.userId;

            $dfHttp.post("api/others/saveSerialNumber.json", serialNumber).success(function (data) {
                $log.debug(data);
                if (data.code == "SUCCESS") {
                    $loading.showSuccess("保存扫码清单成功");
                    $timeout(function () {
                        $loading.hide();
                        $ionicHistory.goBack();
                    }, 500);
                } else {
                    $loading.showError("保存扫码清单失败，请重试");
                }
            }).error(function (e) {
                $loading.showError("网络异常,请稍后再试");
            })
        }

        /**
         * 遍历重构收货数据
         * @param receivingDataForCategory
         * @returns {{userId: string, dataList: Array}|*}
         */
        function getReceivingDataList(receivingDataForCategory) {
            $scope.receivingData.dataList = [];
            angular.forEach(receivingDataForCategory, function (v, k) {
                if (v.length > 0) {
                    angular.forEach(v, function (d, i) {
                        $scope.receivingData.dataList.push(d);
                    })
                }
            })

            return $scope.receivingData;
        }

        /**
         * 遍历重构扫码数据
         * @param serialNumberForCategory
         * @returns {*}
         */
        function getSerialNumberList(serialNumberForCategory) {
            $scope.serialNumber.serialList = [];
            angular.forEach(serialNumberForCategory, function (v, k) {
                if (v.length > 0) {
                    angular.forEach(v, function (d, i) {
                        if (d.categoryCode == "A0302") {
                            checkError(d);
                        }
                        $scope.serialNumber.serialList.push(d);
                    })
                }
            })

            return $scope.serialNumber;
        }

        /**
         * 保存数据
         * @param receivingData
         * @param serialNumber
         * @param userId
         */
        function saveSerialAndRecData(receivingData, serialNumber, userId) {
            $loading.show("正在保存中...");
            $dfHttp.post("api/others/saveSerialAndRecData.json", {
                userId: userId,
                dataList: receivingData.dataList,
                serialList: serialNumber.serialList
            }).success(function (data) {
                if (data.code == "SUCCESS") {
                    $loading.showSuccess("保存收货数据成功");
                    $stateParams.doRefresh();
                    $ionicHistory.goBack();
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (e) {
                $loading.showError("网络异常,请稍后再试");
            });
        }

        // /**
        //  * 保存收货数据
        //  * @param receivingData
        //  */
        // function saveReceivingData(receivingData, serialNumber) {
        //   $loading.show("正在保存收货数据...");
        //   receivingData.userId = $scope.user.userId;
        //
        //   $dfHttp.post("api/others/saveReceivingData.json", receivingData).success(function (data) {
        //     $log.debug(data);
        //     if (data.code == "SUCCESS") {
        //       $loading.showSuccess("保存收货数据成功");
        //
        //       // 保存扫码清单
        //       $timeout(function () {
        //         saveSerialNumber(serialNumber);
        //       }, 500);
        //     } else {
        //       $loading.showError("保存收货数据失败，请重试");
        //     }
        //   }).error(function (e) {
        //     $loading.showError("网络异常,请稍后再试");
        //   })
        // }

        /**
         * 逆变器扫码
         * @param obj
         * @param field
         */
        $scope.scanBarcode = function (obj, field) {
            $rootScope.scanIn = true;
            if (field == "serialNumber") {
                $cordovaBarcodeScanner.scan({
                    //"preferFrontCamera" : true, // iOS and Android
                    //"showFlipCameraButton" : true, // iOS and Android
                    "formats": "QR_CODE,DATA_MATRIX,UPC_E,UPC_A,EAN_8,EAN_13,CODE_128,CODE_39,ITF", // default: all but PDF_417 and RSS_EXPANDED
                    "orientation": "portrait" // Android only (portrait|landscape), default unset so it rotates with the device
                }).then(function (imageData) {
                    if (imageData.text != "") {
                        obj.serialNumber = subSerialNumber(imageData.text);
                        $rootScope.scanIn = false;
                    }
                }, function (error) {
                    $rootScope.scanIn = false;
                    alert("错误");
                });
            } else {
                $cordovaBarcodeScanner.scan({
                    //"preferFrontCamera" : true, // iOS and Android
                    //"showFlipCameraButton" : true, // iOS and Android
                    "formats": "QR_CODE,DATA_MATRIX,UPC_E,UPC_A,EAN_8,EAN_13,CODE_128,CODE_39,ITF", // default: all but PDF_417 and RSS_EXPANDED
                    "orientation": "portrait" // Android only (portrait|landscape), default unset so it rotates with the device
                }).then(function (imageData) {
                    if (imageData.text != "") {
                        obj.serialNumber2 = subSerialNumber(imageData.text);
                        $rootScope.scanIn = false;
                    }
                }, function (error) {
                    $rootScope.scanIn = false;
                    alert("错误");
                });
            }
        }

        /**
         * 扫码列表
         * @param ctgy
         * @param type
         * @param obj
         * @param NBQIndex
         */
        $scope.goScan = function (ctgy, type, obj, NBQIndex) {
            $state.go('tab.task-delivery-scan', {
                args: obj,
                ctgy: ctgy,
                type: type,
                NBQIndex: NBQIndex,
                theFirstElementOfGFZJ: $scope.theFirstElementOfGFZJ,
                receivingDataForGFZJLength: $scope.vm.modulesNum,
                project: $scope.project
            });
        }

        function subSerialNumber(serialNumber) {
            if (serialNumber.indexOf("S/N:") > -1) {
                return serialNumber.substring(4, serialNumber.length);
            }

            return serialNumber;
        }
    })

    //收货扫码
    .controller('DeliveryScanCtrl', function ($rootScope, $scope, $state, $stateParams, $ionicHistory, $loading, $cordovaBarcodeScanner, $timeout, $interval) {
        console.log($stateParams.theFirstElementOfGFZJ);
        $scope.serialList = [];
        $scope.ctgy = $stateParams.ctgy;
        $scope.type = $stateParams.type;
        var NBQIndex = $stateParams.NBQIndex;
        // 跟据ctgy来获取扫码清单
        if ($scope.ctgy == "GFZJ") {
            $scope.serialList = angular.copy($stateParams.args.GFZJ);
        }

        if ($scope.ctgy == "NBQ") {
            $scope.serialList.push(angular.copy($stateParams.args.NBQ[NBQIndex]));
            var theElementOfNBQ = angular.copy($stateParams.args.NBQ[NBQIndex]);
            console.log(theElementOfNBQ);
            if (theElementOfNBQ.serialNumber == undefined
                || theElementOfNBQ.serialNumber == ""
                || theElementOfNBQ.serialNumber2 == undefined
                || theElementOfNBQ.serialNumber2 == "") {
                del(0);
            }
        }

        // 构造序列号的数据结构
        function getSerialNumberObj() {
            return {
                "categoryCode": "",
                "itemCode": "",
                "itemRealCode": "",
                "projectId": "",
                "serialId": "",
                "serialNumber": "",
                "serialNumber2": "",
                "sim1": "",
                "sim2": ""
            }
        }

        $scope.serialNumberObj = getSerialNumberObj();

        /**
         * 删除数组中的元素
         * @param index
         */
        $scope.del = function (index) {
            del(index);
        }

        function del(index) {
            $scope.serialList.splice(index, 1);
        }

        /**
         * 开始扫码
         */
        $scope.scanBarcode = function () {
            $rootScope.scanIn = true;
            $cordovaBarcodeScanner.scan({
                //"preferFrontCamera" : true, // iOS and Android
                //"showFlipCameraButton" : true, // iOS and Android
                "formats": "QR_CODE,DATA_MATRIX,UPC_E,UPC_A,EAN_8,EAN_13,CODE_128,CODE_39,ITF", // default: all but PDF_417 and RSS_EXPANDED
                "orientation": "portrait" // Android only (portrait|landscape), default unset so it rotates with the device
            }).then(function (imageData) {
                if (imageData.text != "") {
                    if ($scope.type == "serialNumber") {
                        $scope.serialNumberObj.serialNumber = subSerialNumber(imageData.text);
                    }

                    if ($scope.type == "serialNumber1") {
                        $scope.serialNumberObj.serialNumber2 = subSerialNumber(imageData.text);
                    }

                    $scope.add();
                    $rootScope.scanIn = false;
                }
            }, function (error) {
                $rootScope.scanIn = false;
                alert("错误");
            });
        }

        /**
         * 添加序列号
         */
        $scope.add = function () {
            if ($scope.ctgy == "GFZJ") {
                if ($stateParams.receivingDataForGFZJLength == $scope.serialList.length) {
                    $loading.showError("实际到货量不能大于总量");
                } else {
                    // 判断输入的序列号是否为空
                    if ($scope.serialNumberObj.serialNumber != "" && $scope.serialNumberObj.serialNumber != null) {
                        var flag = false;

                        //查找重复
                        angular.forEach($scope.serialList, function (d, i) {
                            if (d.serialNumber == $scope.serialNumberObj.serialNumber) {
                                flag = true;
                                return false;
                            }
                        });

                        // 判断是否重复
                        if (flag) {
                            $loading.showError("序列号已存在");
                        } else {
                            var serialNumberObj = getSerialNumberObj();
                            serialNumberObj.serialNumber = $scope.serialNumberObj.serialNumber;
                            serialNumberObj.projectId = $stateParams.project.projectId;
                            // serialNumberObj.projectId = 1000;
                            serialNumberObj.itemCode = $stateParams.theFirstElementOfGFZJ.itemCode;
                            serialNumberObj.categoryCode = $stateParams.theFirstElementOfGFZJ.categoryCode;

                            //数组中添加
                            $scope.serialList.splice(0, 0, serialNumberObj);

                            //清空输入框
                            $scope.serialNumberObj.serialNumber = "";
                        }
                    } else {
                        return;
                    }
                }
            }

            if ($scope.ctgy == "NBQ") {
                var serialNumberObj = getSerialNumberObj();
                serialNumberObj.projectId = theElementOfNBQ.projectId;
                serialNumberObj.itemCode = theElementOfNBQ.itemCode;
                serialNumberObj.itemMeaning = theElementOfNBQ.itemMeaning;
                serialNumberObj.sim1 = theElementOfNBQ.sim1;
                serialNumberObj.sim2 = theElementOfNBQ.sim2;
                serialNumberObj.categoryCode = theElementOfNBQ.categoryCode;

                if ($scope.type == "serialNumber") {
                    if ($scope.serialList.length >= 1) {
                        $loading.showError("实际到货量不能大于总量");
                    } else {
                        if ($scope.serialNumberObj.serialNumber != "" && $scope.serialNumberObj.serialNumber != null) {
                            serialNumberObj.serialNumber2 = theElementOfNBQ.serialNumber2;
                            serialNumberObj.serialNumber = $scope.serialNumberObj.serialNumber;
                            $scope.serialList.push(serialNumberObj);
                            $scope.serialNumberObj.serialNumber = "";
                        } else {
                            return;
                        }
                    }
                }

                if ($scope.type == "serialNumber1") {
                    if ($scope.serialList.length >= 1) {
                        $loading.showError("实际到货量不能大于总量");
                    } else {
                        if ($scope.serialNumberObj.serialNumber2 != "" && $scope.serialNumberObj.serialNumber2 != null) {
                            serialNumberObj.serialNumber = theElementOfNBQ.serialNumber;
                            serialNumberObj.serialNumber2 = $scope.serialNumberObj.serialNumber2;
                            $scope.serialList.push(serialNumberObj);
                            $scope.serialNumberObj.serialNumber2 = "";
                        } else {
                            return;
                        }
                    }
                }
            }
        }
        /**
         * 完成
         */
        $scope.finish = function () {
            if ($scope.ctgy == "GFZJ") {
                $stateParams.args.GFZJ = $scope.serialList;
            }

            if ($scope.ctgy == "NBQ") {
                if ($scope.serialList.length == 0) {
                    if ($scope.type == "serialNumber") {
                        $stateParams.args.NBQ[NBQIndex].serialNumber = undefined;
                    } else {
                        $stateParams.args.NBQ[NBQIndex].serialNumber2 = undefined;
                    }
                } else {
                    $stateParams.args.NBQ[NBQIndex] = $scope.serialList[0];
                }
            }
            $ionicHistory.goBack();
        }

        function subSerialNumber(serialNumber) {
            if (serialNumber.indexOf("S/N:") > -1) {
                return serialNumber.substring(4, serialNumber.length);
            }

            return serialNumber;
        }
    })

    .controller('TaskCtrl', function ($ionicHistory, $cordovaDialogs, $rootScope, $ionicPopup, $user, $region, $log, $scope, $state, $lookup, $task, $http, $dfHttp, $loading, $timeout, $ionicScrollDelegate, ionicDatePicker, $dfBoradcast, $dfUtil, $dfCache, $compile) {
        // 初始化
        $scope.vm = {};
        $scope.vm.search = "";
        $scope.goInputText = function (obj, propName, isDisabled) {
            $state.go('tab.task-common-textarea', {
                args: {
                    obj: obj,
                    propName: propName,
                    isDisabled: isDisabled
                }
            });
        }

        var user = $user.getCurrentUserSync();
        $scope.user = user ;

        $task.getCountOfTasks(user.userId);

        function changeProjectStatus(project, fun) {
            $loading.show("正在改变单据状态...");
            $task.changeStatus($scope.user.userId, project.projectId, project.status).success(function (data) {
                if (data.code == 'SUCCESS') {

                    if (typeof fun == "function") {
                        fun($scope.user.userId);
                    }
                    $task.getCountOfTasks(user.userId)
                    //$scope.items = projects;
                    $loading.showSuccess(data.msg);
                    $scope.doRefresh();
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (data) {
                $loading.showError('网络异常,请稍后再试');
            });
        }

        $scope.call = function (PhoneNumber) {
            $cordovaDialogs.confirm('确认拨打' + PhoneNumber + '?', '拨打电话', ['取消', '拨打']).then(function (buttonIndex) {
                if (buttonIndex == 2) {
                    window.open("tel:" + PhoneNumber);
                }
            })
        }
        $timeout(function () {
            if (!$scope.user) {
                $scope.user = $user.getCurrentUserSync();
            }
            $scope.vm.choiceBtn = $task.showChoiceBtn($scope.user);
        }, 300);
        /**
         * 初始化
         */
        $scope.$on('$stateChangeSuccess', function () {
            if (!$scope.user) {
                $scope.user = $user.getCurrentUserSync();
            }
            $timeout(function () {
                $scope.vm.choiceBtn = $task.showChoiceBtn($scope.user);
            }, 1);
        });

        $scope.$on('$ionicView.beforeEnter', function () {
            $ionicHistory.clearHistory();
            $ionicHistory.clearCache(['tab.task-survey']);
            //$state
        });


        $scope.init = function () {
            $scope.isCanLoadMore = true;
        }

        $scope.btnShow = function (btnClass, item) {
            if (!$scope.user || !$scope.user.RoleMember) {
                return false;
            }
            return $task.showTaskBtn($scope.user.RoleMember, item ? item.status : undefined, btnClass);
        }

        //搜索
        $scope.projectFilter = function (item) {
            // 判断搜索内容
            if ($scope.vm.search != "") { //空
                if ((!angular.isUndefined(item.projectNumber) && item.projectNumber.indexOf($scope.vm.search) >= 0)//项目编号
                    || (!angular.isUndefined(item.statusDesc) && item.statusDesc.indexOf($scope.vm.search) >= 0) //状态
                    || (!angular.isUndefined(item.customerName) && item.customerName.indexOf($scope.vm.search) >= 0) //客户名称
                    || (!angular.isUndefined(item.contacts) && item.contacts.indexOf($scope.vm.search) >= 0) //联系人
                    || (!angular.isUndefined(item.contactsTel) && item.contactsTel.indexOf($scope.vm.search) >= 0) //联系电话
                    || (!angular.isUndefined(item.address) && item.address.indexOf($scope.vm.search) >= 0) //地址
                    || (!angular.isUndefined(item.regionDesc) && item.regionDesc.indexOf($scope.vm.search) >= 0)) { //所属地区
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        }


        var taskView = document.getElementById('taskView');
        //content opations
        var contentOpations = {
            animateType: 'slideIn',    //动画类型
            contentBgOpacity: '.7',   //背景透明度
            contentBgcolor: '#fff',   //背景颜色
            animateDuration: '.5s',  //动画时常
            templateUrl: 'templates/project-track/project-track-content.html'    //模版url
        };
        //content init
        var defineContent = new DefineContent(contentOpations);

        $scope.$on("hideContent", function () {
            $scope.hideContent();
        })

        $scope.hideContent = function () {
            $timeout(function () {
                $rootScope.isProjectTrackContent = false;
                $rootScope.isProjectTract = false;
                $timeout(function () {
                    $scope.vm.trackScope.$destroy();
                }, 1000);
                defineContent.deleteSelf();
                $rootScope.defeineContentLazyLoad = false;
                $scope.vm.showContent = false;
                $rootScope.devinHideTabs = false;
            }, 300);
        };

        // 点击项目编号显示项目档案
        $scope.goToTaskFollow = function (item) {
            window.currentPorjectInfo = item;

            //return [0]content  [1]contentBg
            $scope.vm.contents = defineContent.addInto(taskView);
            $scope.vm.trackScope = $scope.$$childHead.$new();

            $timeout(function () {
                var element = $compile($scope.vm.contents[0])($scope.vm.trackScope);
                $scope.vm.showContent = true;
                $rootScope.devinHideTabs = true;
            }, 300)

            // $state.go('^.project-track-content', { args: item }, { reload: true });
        };


        function clearStatu() {
            $scope.isTodo = false;
            $scope.isOnline = false;
            $scope.isChoice = false;
            $scope.isCheck = false;
        }

        /**
         * 加载数据,根据状态
         * @param status
         */
        $scope.getProjectListWithStatus = function (status, event) {

            //切换时,滚动到顶部
            $ionicScrollDelegate.scrollTop();


            $scope.status = status;

            switch (status) {
                case 'FOR_ORDER':
                    if ($scope.isTodo && event) {
                        return;
                    }
                    $task.getCountOfTasks(user.userId);
                    $scope.items = [];
                    clearStatu();
                    $scope.isTodo = true;
                    break;
                case 'ON_GOING':
                    if ($scope.isOnline && event) {
                        return;
                    }
                    $task.getCountOfTasks(user.userId);
                    $scope.items = [];
                    clearStatu();
                    $scope.isOnline = true;
                    break;
                case 'FOR_ASSIGN':
                    if ($scope.isChoice && event) {
                        return;
                    }
                    $task.getCountOfTasks(user.userId);
                    $scope.items = [];
                    clearStatu();
                    $scope.isChoice = true;
                    break;
                case 'IS_CHECK':
                    if ($scope.isCheck && event) {
                        return;
                    }
                    $task.getCountOfTasks(user.userId);
                    $scope.items = [];
                    clearStatu();
                    $scope.isCheck = true;
                    break;
            }
            //清空搜索框
            $scope.vm.search = "";

            $scope.doRefresh();
        };

        $scope.items = [];

        /**
         * 下拉刷新
         */
        $scope.doRefresh = function () {
            $user.getCurrentUser().executeSuccess(function (user) {
                $task.getTaskList(user.userId, $scope.status)
                    .success(function (data) {
                        if (data.options.listType !== $scope.status) {
                            return;
                        }
                        if (data.code == "SUCCESS") {
                            $scope.items = [];
                            angular.forEach(data.data, function (project) {
                                $lookup.getWithLookupCode(project.status).executeSuccess(function (lookup) {
                                    project.statusDesc = lookup.lookupMeaning;
                                });
                                var region = $region.getWithRegion(project.regionCode);
                                project.regionDesc = '' + region.provinceName + region.cityName + region.regionName;
                                $scope.items.push(project);
                            });
                        } else {
                            $loading.showError("加载数据失败");
                        }
                        $scope.isCanLoadMore = true;
                        $scope.$broadcast('scroll.refreshComplete');
                        $task.getCountOfTasks(user.userId);
                    }).error(function (data) {
                        $loading.showError("加载数据失败");
                        $scope.$broadcast('scroll.refreshComplete');
                    });
            });
        }

        /**
         * 上拉加载
         */
        $scope.loadMore = function () {
            $scope.$broadcast('scroll.infiniteScrollComplete');
        };

        /**
         * 是否可以加载数据
         * @returns {boolean}
         */
        $scope.moreDataCanBeLoaded = function () {
            return $scope.isCanLoadMore;
        }

        /**
         * 选择日期,需真机测试
         */
        $scope.choiceDate = function (item) {
            var options = {
                callback: function (val) { //Mandatory
                    item.planDate = $dfUtil.convertDateToString(new Date(val));
                    $dfHttp.post("api/project/saveProjectPlanDate.json", {
                        userId: $scope.user.userId,
                        projectId: item.projectId,
                        planDate: item.planDate
                    })
                }
            }
            ionicDatePicker.openDatePicker(options);
        }

        //意向
        $scope.forwardIntention = function (project) {
            $state.go('tab.task-intention', { args: project });
            //$dfBoradcast.sendBoradcast('taskChange',{args:project});
        }

        //跟进
        $scope.forwardFollow = function (project) {
            $state.go('tab.task-follow', { args: project });
            //$dfBoradcast.sendBoradcast('taskChange',{args:project});
        }

        //接单
        $scope.forwardRecive = function (project) {
            $cordovaDialogs.confirm('确认接单?', '接单', ['取消', '确认']).then(function (buttonIndex) {
                if (buttonIndex == 2) {
                    changeProjectStatus(project);
                }
            });
        }
        // 并网验收
        $scope.forwardCheckAndReceive = function (project) {
            $state.go('tab.task-checkAndReceive', { args: project, doRefresh: $scope.doRefresh });
        }
        //项目日志
        $scope.forwardProjectLog = function (project) {
            $state.go('tab.project-log', { args: project });
        }

        //项目审核
        $scope.approveProject = function (project) {
            var statuDis = project.statusDesc.substr(0, project.statusDesc.length - 1);

            $cordovaDialogs.confirm('确定通过?', '项目' + statuDis, ['取消', '确定通过']).then(function (buttonIndex) {

                if (buttonIndex == 2) {
                    var params = {
                        'userId': $scope.user.userId,
                        'projectId': project.projectId,
                        'approveStatus': 'APPROVED',
                        'approveReason': '审核通过',
                        'LogType': '方案审核'
                    };
                    $dfHttp.post('api/others/approveDesign.json', params).success(function (data) {
                        if (data.code == "SUCCESS") {
                            $loading.showSuccess(data.msg);
                            $rootScope.listStatus = "IS_CHECK";
                            $task.getCountOfTasks(user.userId);
                        } else {
                            $loading.showError(data.msg);
                        }
                    }).error(function (data) {
                        $loading.showError('网络异常,请稍后再试');
                    });
                }
            });
            //$scope.checkPopup = $ionicPopup.show({
            //  title: '项目'+statuDis,
            //  subTitle: '确定通过?',
            //  scope: $scope,
            //  buttons: [
            //    { text: '取消',type:"gray-bg"},
            //    {
            //      text: '<b>通过</b>',
            //      type: 'button-positive',
            //      onTap: function() {
            //        var params = {
            //          'userId':$scope.user.userId,
            //          'projectId':project.projectId,
            //          'approveStatus':'APPROVED',
            //          'approveReason':'',
            //          'LogType':'方案审核'
            //        };
            //        $dfHttp.post('api/others/approveDesign.json',params).success(function(data){
            //          if(data.code == "SUCCESS") {
            //            $loading.showSuccess(data.msg);
            //          } else {
            //            $loading.showError(data.msg);
            //          }
            //          changeProjectStatus(project,getcount);
            //        }).error(function(data) {
            //          $loading.showError('网络异常,请稍后再试');
            //        });
            //      }
            //    }
            //  ]
            //});
        }
        $scope.vm = {};
        $scope.vm.rejectReason = '';
        $scope.rejectProject = function (project) {
            console.log(project);
            var statuDis = project.statusDesc.substr(0, project.statusDesc.length - 1);
            $scope.checkPopup = $ionicPopup.show({
                template: '<input style="font-size: 14px" ng-model="vm.rejectReason" placeholder="请输入不通过的原因">',
                title: '项目' + statuDis,
                subTitle: '确定拒绝?',
                scope: $scope,
                buttons: [
                    { text: '取消', type: 'button-dark button-ligthDark' },
                    {
                        text: '<b>拒绝</b>',
                        type: 'button-assertive',
                        onTap: function (e) {

                            if ($scope.vm.rejectReason == "") {
                                e.preventDefault();
                                return;
                            } else {
                                var params = {
                                    'userId': $scope.user.userId,
                                    'projectId': project.projectId,
                                    'approveStatus': 'REJECTED',
                                    'approveReason': $scope.vm.rejectReason,
                                    'LogType': '方案审核'
                                };
                                $dfHttp.post('api/others/approveDesign.json', params).success(function (data) {
                                    if (data.code == "SUCCESS") {
                                        $scope.vm.rejectReason = '';
                                        $loading.showSuccess(data.msg);
                                        $rootScope.listStatus = "IS_CHECK";
                                        $task.getCountOfTasks(user.userId);
                                    }
                                });
                            }
                        }
                    }
                ]
            });
        }

        $scope.hidePop = function () {
            $scope.checkPopup.close();
        }

        //发起勘察
        $scope.forwardSendSurvey = function (project) {
            $cordovaDialogs.confirm('确认发起勘察?', '发起勘察', ['取消', '确认']).then(function (buttonIndex) {
                if (buttonIndex == 2) {
                    changeProjectStatus(project);
                }
            });
        }

        //进入勘察
        $scope.forwardSurvey = function (project) {
            if (project.latitude && project.longitude) {
                $state.go('tab.task-survey', { args: project });
            } else {
                $state.go('tab.task-position-submit', { args: project });
            }
        }

        //完成勘察
        $scope.forwardFinishSurvey = function (project) {
            var data = $dfCache.getObject('surveyInfo$' + project.projectId);
            if (data.uploaded) {
                $cordovaDialogs.confirm('确认已完成勘察?', '完成勘察', ['取消', '确认']).then(function (buttonIndex) {
                    if (buttonIndex == 2) {
                        changeProjectStatus(project);
                    }
                });
            } else {
                $cordovaDialogs.confirm('勘察信息未提交,请提交后重试!', '完成勘察', ['取消', '确认']).then(function (buttonIndex) {
                    if (buttonIndex == 2) {
                        $scope.forwardSurvey(project);
                    }
                });
            }
        }

        //提交审核
        $scope.forwardSubmitDesign = function (project) {
            $cordovaDialogs.confirm('确认提交审核?', '提交审核', ['取消', '确认']).then(function (buttonIndex) {
                if (buttonIndex == 2) {
                    changeProjectStatus(project);
                    $task.getCountOfTasks(user.userId)
                }
            });
        }


        //查看跟进
        $scope.forwardLookFollow = function (project) {
            project.disable = true;
            $state.go('tab.task-follow', { args: project });
        }

        //方案设计
        $scope.forwardDesign = function (project) {
            $state.go('tab.task-design', { args: project });
        }

        //取消意向
        $scope.forwardCancel = function (project) {
            //changeProjectStatus(project);
            //取消项目
            $scope.showCancelPopup = $ionicPopup.show({
                template: '<input id="cancelReason" type="text" ng-model="cancelReason"/>',
                title: '取消意向',
                subTitle: '请输入取消原因',
                scope: $scope,
                buttons: [
                    {
                        text: '取消', type: "gray-bg",
                        onTap: function (e) {
                            //e.preventDefault();
                            return;
                        }
                    },
                    {
                        text: '<b>确认</b>',
                        type: 'button-positive',
                        onTap: function (e) {
                            var cancelReason = document.getElementById('cancelReason').value;
                            if (cancelReason && cancelReason != '') {
                                return cancelReason;
                            } else {
                                e.preventDefault();
                            }
                        }
                    }
                ]
            });
            $scope.showCancelPopup.then(function (res) {
                if (!res || res == '') {
                    return;
                }
                //console.log('取消意向',res);
                $loading.show("正在取消意向");
                $task.cancelProject($scope.user.userId, project.projectId, res)
                    .success(function (data) {
                        if (data.code == 'SUCCESS') {
                            $loading.showSuccess(data.msg);
                            $task.getCountOfTasks($scope.user.userId)
                            $scope.doRefresh();
                        } else {
                            $loading.showError(data.msg);
                        }
                    }).error(function (data) {
                        $loading.showError('网络异常,请稍后再试');
                    });
            });
        }
        // 项目分配
        $scope.forwardAssigned = function (project) {
            $state.go('tab.task-to-be-assigned', { args: project });
        }
        $scope.forwardDelivery = function (project) {
            $state.go('tab.task-delivery', { args: project, doRefresh: $scope.doRefresh });
        }
        // 进度报告
        $scope.forwardProgressReport = function (project) {
            $state.go('tab.task-progressReport', { args: project, doRefresh: $scope.doRefresh });
        }
        $scope.forwardCheckProject = function (project) {
            $state.go('tab.task-checkProject', { args: project });
        }
        // 合同签订
        $scope.forwardContractSign = function (project) {
            $state.go('tab.task-contract-sign', { args: { project: project, doRefresh: $scope.doRefresh } });
        }
        $scope.forwardAgreeComplete = function (project) {
            $cordovaDialogs.confirm('确认同意完工？', '完工确认', ['取消', '确认']).then(function (buttonIndex) {
                if (buttonIndex == 2) {
                    changeProjectStatus(project);
                    $task.getCountOfTasks(user.userId);
                }
            });
        }


        // 发货
        $scope.forwardSendTheGoods = function (project) {
            $scope.sendTheGoodsInfo = {
                sendTime: "",
                receipeTime: "",
                logisticsInfo: ""
            }

            // 确认发货选择日期
            $scope.choiceDate = function (obj, column) {
                var chooseDate = "";

                var options = {
                    callback: function (val) {
                        chooseDate = $dfUtil.convertDateToString(new Date(val));
                        if (column == "sendTime") {
                            obj.sendTime = chooseDate;
                        }

                        if (column == "receipeTime") {
                            obj.receipeTime = chooseDate;
                        }
                    }
                }
                ionicDatePicker.openDatePicker(options);
            }

            var Popup = $ionicPopup.show({
                title: '确认发货？',
                template: "<p>发货时间<input type='text' ng-model='sendTheGoodsInfo.sendTime' placeholder='请选择发货时间' readonly='readonly' ng-click='choiceDate(sendTheGoodsInfo, \"sendTime\")' /></p>" +
                "<p>预计到货时间<input type='text' ng-model='sendTheGoodsInfo.receipeTime' placeholder='请选择预计到货时间' readonly='readonly' ng-click='choiceDate(sendTheGoodsInfo, \"receipeTime\")' /></p>" +
                "<p>物流信息<textarea ng-model='sendTheGoodsInfo.logisticsInfo' rows='5' placeholder='请填写物流信息'></textarea></p>",
                scope: $scope,
                buttons: [
                    { text: '取消', type: 'gray-bg', },

                    {
                        text: '确认',
                        type: 'button-positive',
                        onTap: function (e) {
                            e.preventDefault();

                            if ($scope.sendTheGoodsInfo.sendTime == "" || $scope.sendTheGoodsInfo.receipeTime == "" || $scope.sendTheGoodsInfo.logisticsInfo == "") {
                                return;
                            }

                            $dfHttp.post("api/others/sendTheGoods.json", {
                                "userId": $scope.user.userId,
                                "projectId": project.projectId,
                                "sendTime": $scope.sendTheGoodsInfo.sendTime,
                                "receipeTime": $scope.sendTheGoodsInfo.receipeTime,
                                "logisticsInfo": $scope.sendTheGoodsInfo.logisticsInfo
                            }).success(function (d) {
                                if (d.code == "SUCCESS") {
                                    $loading.showSuccess("保存成功");
                                    $rootScope.listStatus = 'ON_GOING';
                                    $task.getCountOfTasks(user.userId);
                                    Popup.close();
                                } else {
                                    $loading.showError("保存失败");
                                }
                            }).error(function (e) {
                                $loading.showError("网络异常,请稍后再试");
                            });
                        }
                    }
                ]
            })
        }
        // 方案整改
        $scope.forwardCorrection = function (project) {
            getDesignRectification(project.projectId, $scope.user.userId);

            /**
             * 获取整改
             * @param projectId
             * @param userId
             */
            function getDesignRectification(projectId, userId) {
                $loading.show("获取数据中");
                $dfHttp.get("api/others/getDesignRectification.json", {
                    projectId: projectId,
                    userId: userId
                }).success(function (data) {
                    if (data.code == "SUCCESS") {
                        $scope.spmsReform = data.data;
                        if (angular.isUndefined($scope.spmsReform.projectId)) {
                            $scope.spmsReform.projectId = projectId;
                        }
                        if (angular.isUndefined($scope.spmsReform.reformResult)) {
                            $scope.spmsReform.reformResult = "";
                        } else {
                            $scope.spmsReform.reformResult = $scope.spmsReform.reformResult + "";
                        }
                        $loading.hide();
                        showPopup();
                    } else {
                        $loading.showError(data.msg);
                    }
                }).error(function (e) {
                    $loading.showError("网络有点小问题，请稍后再试");
                })
            }

            /**
             * 保存整改
             * @param spmsReform
             */
            function saveDesignRectification(spmsReform, popup) {
                $loading.show("保存中...");
                $dfHttp.post("api/others/saveDesignRectification.json", spmsReform)
                    .success(function (data) {
                        if (data.code == "SUCCESS") {
                            $loading.showSuccess(data.msg);
                            popup.close();
                            $task.getCountOfTasks(user.userId);
                            $rootScope.listStatus = "IS_CHECK";
                        } else {
                            $loading.showError(data.msg);
                        }
                    }).error(function (e) {
                        console.log(e);
                        $loading.showError("网络有点小问题，请稍后再试");
                    })
            }


            function showPopup() {
                var popup = $ionicPopup.show({
                    title: "要求整改",
                    subTitle: "请输入方案整改意见",
                    template: "<textarea id='correctionIdea' placeholder='请输入整改意见' rows='5' style='overflow: hidden;resize: none;'>{{spmsReform.reformInfo}}</textarea>",
                    scope: $scope,
                    buttons: [
                        { text: '取消', type: "gray-bg" },
                        {
                            text: '确认',
                            type: 'button-positive',
                            onTap: function (e) {
                                e.preventDefault();
                                var correctionIdea = $dfUtil.trimStr(document.getElementById("correctionIdea").value);
                                if (correctionIdea == "") {
                                    return;
                                }
                                if ("" != correctionIdea || angular.isUndefined(!correctionIdea)) {
                                    $scope.spmsReform.reformInfo = correctionIdea;
                                    $scope.spmsReform.userId = $scope.user.userId;
                                    $scope.spmsReform.reform_approve = "N";
                                    saveDesignRectification($scope.spmsReform, popup);
                                } else {
                                    $loading.hide();
                                }
                            }
                        }
                    ]
                });
            }
        }

        //方案整改中
        $scope.forwardCorrectionIng = function (project) {
            $state.go("tab.task-correction", { args: { project: project } });
        }

        // 工程量变更
        $scope.forwardQutyChange = function (entry, project) {
            $state.go("tab.task-qutyChange", { args: { entry: entry, project: project } });
        }

        // 变更审核
        $scope.forwardQutyChangeAuditing = function (entry, project) {
            $state.go("tab.task-qutyChange", { args: { entry: entry, project: project } });

        }

        // 启动施工
        $scope.startConstruction = function (project) {
            $scope.vm.remarkForConstruction = "";
            var popup = $ionicPopup.show({
                template: '<textarea rows="5" style="overflow:hidden;resize:none;" ng-trim="true" ng-model="vm.remarkForConstruction" placeholder="请填写施工备注"></textarea>',
                title: '是否启动施工？',
                scope: $scope,
                buttons: [
                    {
                        text: '取消',
                        type: "gray-bg",
                    },
                    {
                        text: '确认',
                        type: 'button-positive',
                        onTap: function (e) {
                            e.preventDefault();
                            saveSetupRemark(project.projectId, $scope.user.userId, $scope.vm.remarkForConstruction, popup);
                            changeProjectStatus(project);
                            $task.getCountOfTasks(user.userId);
                        }
                    }
                ]
            })

            /**
             * 保存施工意见
             * @param remark
             */
            function saveSetupRemark(projectId, userId, remarkForConstruction, popup) {
                $loading.show("正在保存中...");
                $dfHttp.post("api/others/saveSetupRemark.json", {
                    projectId: projectId,
                    userId: userId,
                    setupRemark: remarkForConstruction
                }).success(function (data) {
                    if (data.code == "SUCCESS") {
                        $loading.showSuccess("保存施工意见成功");
                        popup.close();
                        changeProjectStatus(project);
                        $task.getCountOfTasks(user.userId);
                    } else {
                        $loading.showError("保存失败");
                    }
                }).error(function (e) {
                    $loading.showError("网络异常，请稍候再试");
                });
            }
        }

        //$scope.$on('taskChange',function (event, msg) {
        //  console.log("taskChange emit",event,msg);
        //  //$scope.ctr1Name = msg;
        //});
        $dfBoradcast.getBoradcast('TaskIntentionCreateCtrl.taskChange', function (data) {
            console.log(data);
        });

        // 跳转到提交

        $scope.$watch('listStatus', function (newValue) {
            $log.log(newValue);
            if (newValue === 'FOR_ORDER' || newValue === 'ON_GOING' || newValue === 'FOR_ASSIGN' || newValue === 'IS_CHECK') {
                $scope.getProjectListWithStatus(newValue);
                $rootScope.listStatus = undefined;
                $log.log(newValue);
            }
        })

        $scope.getProjectListWithStatus('FOR_ORDER');

        $lookup.syncLookup();
    })
    //创建销售意向ctrl
    .controller('TaskIntentionCreateCtrl', function ($rootScope, $dfHttp, $ionicHistory, $cordovaDialogs, $ionicActionSheet, $user, $loading, $timeout, $scope, $log, $task, $stateParams, $state, $lookup, $dfBoradcast, modalsService, $dfUtil) {
        $scope.electricity = "electricity";

        var user = $user.getCurrentUserSync();
        $scope.user = user;
        $scope.goInputText = function (obj, propName) {
            $state.go('tab.task-common-textarea', {
                args: {
                    obj: obj,
                    propName: propName
                }
            });
        }

        $scope.goChoice = function (type, current) {
            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current
                }
            });
        };


        //获取销售意向
        var projectIntention = {
            "userId": -1,
            "customerName": "",
            "contacts": "",
            "projectType": "",
            "projectTypeDis": "",
            "contactsTel": "",
            "distributorCode": "",
            "salesId": "",
            "techId": "",
            "installerCode": "",
            "installerId": "",
            "status": "",
            "regionCode": "",
            "address": "",
            "supportingPoorFlag": "N",
            "town": "",
            "village": "",
            "remark": "",
            "resource": "",
        }

        if ($stateParams.args.projectId) {
            //console.log($stateParams.args+'has');
            angular.copy($stateParams.args, projectIntention);
            if (projectIntention.supportingPoorFlag == 'Y') {
                projectIntention.supportingPoorFlagDesc = '是'
            } else {
                projectIntention.supportingPoorFlag = 'N';
                projectIntention.supportingPoorFlagDesc = '否'
            }
        }
        $user.getCurrentUser().executeSuccess(function (user) {
            $scope.user = user;
            projectIntention.userId = user.userId;
            // user.autoLogin = false ;
            // $user.saveUser(user);
            //$task.getProjectIntention(user.userId,1007).success(function(data){
            //  console.log(data);
            //});
        });

        //$scope.projectIntention.userId = $user.getCurrentUser().userId ;

        //$scope.goChoiceWithRegion = function() {
        //  $state.go('tab.task-common-choice',{'args':{'lookupType':'CUSTOMER_EXPECTATION','currentCode':'OTHER','showOther':true,'otherName':'其他','otherValue':'恒大'}});
        //}

        var poorList = [
            { text: '是', value: 'Y' },
            { text: '否', value: 'N' }
        ];

        $scope.choicePoor = function () {
            $scope.hidePoor = $ionicActionSheet.show({
                buttons: poorList,
                //destructiveText: 'Delete',
                //titleText: 'Modify your album',
                cancelText: '取消',
                buttonClicked: function (index) {
                    $scope.projectIntention.supportingPoorFlagDesc = poorList[index].text;
                    $scope.projectIntention.supportingPoorFlag = poorList[index].value;
                    return true;
                }
            })
        };

        $scope.goChoiceWithRegion = function () {
            modalsService.choiceCity({
                events: {
                    ok: 'date-modal:ok',
                    cancel: 'date-modal:cancel'
                }
            });
        };

        $scope.$on("date-modal:ok", function (event, data) {
            $timeout(function () {
                //$scope.projectIntention.region = 123;
                $scope.projectIntention.regionDesc = data.pro.provinceName + data.city.cityName + data.town.regionName;
                $scope.projectIntention.regionCode = data.town.regionCode;
            }, 1);
        });

        $scope.$on("date-modal:cancel", function (event, data) {
        });

        //获取当前用户信息
        var user = $user.getCurrentUserSync();
        $scope.projectIntention = projectIntention;

        $scope.submitIntention = function () {
            $loading.show('保存销售意向.');
            $task.createProjectIntention($scope.projectIntention).success(function (data) {
                if (data.code == 'SUCCESS') {
                    //$dfBoradcast.sendBoradcast('TaskIntentionCreateCtrl.taskChange', {'args': $scope.projectIntention});
                    for (var key in $stateParams.args) {
                        $stateParams.args['' + key + ''] = $scope.projectIntention['' + key + ''];
                    }
                    $loading.showSuccess('保存成功');

                    $ionicHistory.goBack();
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (data) {
                $loading.showError('网络异常,请稍后再试');
            });
        }

        $scope.$on('$stateChangeSuccess', function () {
            $scope.projectIntention.choiceItem = $lookup.getChoiceItem();

            if (!$dfUtil.isEmptyObject($scope.projectIntention.choiceItem)) {
                //获取指定参数,如果不存在就不处理
                $timeout(function () {
                    $scope.projectIntention.projectType = $scope.projectIntention.choiceItem.code;
                    $scope.projectIntention.projectTypeDis = $scope.projectIntention.choiceItem.meaning;
                }, 10);
            }
            $lookup.clearChoiceItem();
        });

        /**
         * 输入完客户名称后，自动给客户联系人赋值
         * @param customerName
         */
        $scope.setContacts = function (customerName) {
            if (!$scope.projectIntention.contacts || $scope.projectIntention.contacts == "") {
                $scope.projectIntention.contacts = customerName;
            }
        }
    })

    .controller('TaskFollowCtrl', function ($dfUtil, $timeout, $cordovaDialogs, $ionicHistory, $scope, $log, $task, $stateParams, $user, $dfHttp, $state, $loading, $lookup, $imageUploadCache, $cordovaFile, $interval) {
        $scope.projectIntention = {
            "buildingHeight": "",
            "customerExpectation": "",
            "floors": "",
            "fwjg": "",
            "jhjt": "",
            "jsf": "",
            "jzjgnf": "",
            "kfs": "",
            "preSurveyId": "",
            "projectId": "",
            "propertyRight": "",
            "wdhz": "",
            "wdjg": "",
            "wdjgQt": "",
            "wdlx": "",
            "zwgd": "",
            "zwwz": "",
            "userId": "",
            "remark": "",
            "imageURL": []
        };

        $scope.vm = {};
        $scope.vm.disable = $stateParams.args.disable;

        $scope.goInputText = function (obj, propName, isDisabled) {
            $state.go('tab.task-common-textarea', {
                args: {
                    obj: obj,
                    propName: propName,
                    isDisabled: isDisabled
                }
            });
        }

        $scope.savePre = function () {
            var showMsg = "";
            var photoDatasArray = [];
            $loading.show('数据提交中..');
            $scope.projectIntention.userId = $scope.user.userId;
            $dfHttp.post("api/survey/createOrUpdatePreSurvey.json", $scope.projectIntention).success(function (data) {
                if (data.code == 'SUCCESS') {
                    //$loading.showSuccess(data.msg);
                    showMsg = data.msg;
                    //从缓存中获取图片url,并从文件读取图片。
                    var imageCache = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, 'PROJECT', 'JHJTT');
                    if (!imageCache.images) {
                        imageCache.images = [];
                    }
                    var imageCacheCount = imageCache.images.length;
                    angular.forEach(imageCache.images, function (image) {
                        if (image.resource == 'NETWORK') {
                            imageCacheCount--;
                            return;
                        }
                        var pickImage = image.imageUrl;

                        var lastIndexOfSlash = pickImage.lastIndexOf('/');
                        var filePath = pickImage.substr(0, lastIndexOfSlash); //p
                        var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

                        $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
                            var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
                            photoDatasArray.push(base64String);
                        }, function (error) {
                            console.log(error);
                            $loading.showError('本地图片没有找到,请确认存在');
                        });

                    });

                    if (!imageCache.images) {
                        imageCache.images = [];
                    }
                    if (imageCache.images.length == 0) {
                        $loading.showSuccess(data.msg);
                        $ionicHistory.goBack();
                        return;
                    }


                    $loading.show('图片提交中..');
                    $scope.timer = $interval(function (e) {
                        if (photoDatasArray.length == imageCacheCount) {
                            $task.uploadImage('PROJECT', $scope.projectIntention.projectId, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray)
                                .success(function (data) {
                                    if (data.code == 'SUCCESS') {
                                        $loading.showSuccess(showMsg ? showMsg : data.msg);
                                        $ionicHistory.goBack();
                                    } else {
                                        $loading.showError(data.msg);
                                    }
                                }).error(function (data) {
                                    $loading.showError('网络异常,请稍后再试');
                                });
                            $interval.cancel($scope.timer);
                        }
                    }, 200, 10);


                    //确认图片是否全部读取成功,如果全部读取成功则上传,图片。否则提示文件可能不存在

                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (data) {
                $loading.showSuccess("请检查网络设置");
            });

        }

        $user.getCurrentUser().executeSuccess(function (user) {

            $loading.show("加载中...");

            $scope.user = user;
            $scope.projectIntention.userId = user.userId;
            $scope.projectIntention.projectId = $stateParams.args.projectId;
            $dfHttp.get("api/survey/getPreSurvey.json", {
                "userId": $scope.projectIntention.userId,
                "projectId": $stateParams.args.projectId
            }).success(function (data) {
                if (data.code == 'SUCCESS') {
                    $loading.hide();
                    $scope.projectIntention.userId = $scope.user.userId;

                    if (data.data && data.data.preSurveyId) {
                        for (var key in $scope.projectIntention) {
                            $scope.projectIntention['' + key + ''] = data.data['' + key + ''];
                            if (key == 'jsf') {
                                if (data.data.jsf == "OTHER") {
                                    $scope.projectIntention.jsfDis = '开发商 ' + data.data.kfs;
                                }

                            } else if (key == 'wdjg') {
                                $scope.projectIntention.wdjgDis = '其他';
                            }
                        }

                        for (item in $scope.projectIntention) {
                            $lookup.getWithLookupCode($scope.projectIntention['' + item + ''], item).executeSuccess(function (lookup) {
                                if (lookup.lookupCode) {
                                    $scope.projectIntention['' + lookup.options + 'Dis'] = lookup.lookupMeaning;
                                }
                            })
                        }

                        //if(angular.isArray($scope.projectIntention.imageURL) && $scope.projectIntention.imageURL.length > 0){
                        //    $scope.vm.showImageDesc = 'HAS_IMAGE';
                        //}else{
                        //    $scope.vm.showImageDesc = '';
                        //}
                        //文件

                        var imageCache = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, 'PROJECT', 'JHJTT');
                        if (!imageCache.images) {
                            imageCache.funId = $scope.projectIntention.projectId;
                            imageCache.funName = 'PROJECT';
                            imageCache.imageClass = 'JHJTT';
                        }
                        imageCache.images = [];
                        angular.forEach($scope.projectIntention.imageURL, function (netImage) {
                            var image = {};
                            image.imageUrl = netImage.middleImageUrl;
                            image.largeImageUrl = netImage.largeImageUrl;
                            image.smallImageUrl = netImage.smallImageUrl;
                            image.uuid = netImage.uuid;
                            image.status = 'NEW';
                            image.resource = 'NETWORK';

                            imageCache.images.push(image);
                        });
                        $imageUploadCache.saveImages(imageCache);
                        if (imageCache.images && imageCache.images.length > 0) {
                            $scope.vm.showImageDesc = 'HAS_IMAGE';
                        } else {
                            $scope.vm.showImageDesc = '';
                        }
                    }
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (data) {
                $loading.showError('网络异常,请稍后再试');
            });
        });

        $scope.images = [];

        //fileReader.readAsDataURL()
        $scope.choiceImage = function (imageClass) {
            if ($imageUploadCache.getImagesCount($scope.projectIntention.projectId, 'PROJECT', imageClass) <= 0) {
                $state.go('tab.task-common-photo', {
                    args: {
                        funId: $scope.projectIntention.projectId,
                        funName: 'PROJECT',
                        imageClass: imageClass
                    }
                });
            } else {
                $state.go('tab.task-common-photo', {
                    args: {
                        funId: $scope.projectIntention.projectId,
                        funName: 'PROJECT',
                        imageClass: imageClass
                    }
                });
            }
        };

        $scope.lookImage = function (imageClass) {
            $state.go('tab.task-common-photo', {
                args: {
                    funId: $scope.projectIntention.projectId,
                    funName: 'PROJECT',
                    imageClass: imageClass
                },
                disable: true
            });
        }
        //netImages: $scope.projectIntention.imageURL

        $scope.goChoice = function (type, current) {
            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current
                }
            });
        };
        $scope.goChoiceWithOther = function (type, current, otherTitle, otherHolder) {
            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current,
                    'showOther': true,
                    'otherName': otherTitle,
                    'otherValue': otherHolder
                }
            });
        };

        if ($stateParams.taskId) {
            $task.createProjectIntention($scope.projectIntention);
        }

        $scope.$on('$stateChangeSuccess', function () {

            if ($imageUploadCache.getImagesCount($scope.projectIntention.projectId, 'PROJECT', 'JHJTT') > 0) {
                $timeout(function () {
                    $scope.vm.showImageDesc = 'HAS_IMAGE';
                }, 1);
            } else {
                $scope.vm.showImageDesc = '';
            }

            //获取指定参数,如果不存在就不处理
            $scope.projectIntention.choiceItem = $lookup.getChoiceItem();
            if ($scope.projectIntention.choiceItem) {

                switch ($scope.projectIntention.choiceItem.type) {

                    case 'CUSTOMER_EXPECTATION':
                        $scope.projectIntention.customerExpectation = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.customerExpectationDis = $scope.projectIntention.choiceItem.meaning;
                        break;
                    case 'PROPERTY_RIGHT':
                        $scope.projectIntention.propertyRight = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.propertyRightDis = $scope.projectIntention.choiceItem.meaning;
                        break;
                    case 'CONSTRUCTION':
                        $scope.projectIntention.jsf = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.jsfDis = $scope.projectIntention.choiceItem.meaning;
                        //$scope.projectIntention.kfs = $scope.projectIntention.choiceItem.meaning;

                        if ($scope.projectIntention.jsf == 'OTHER') {
                            $scope.projectIntention.kfs = $scope.projectIntention.choiceItem.meaning;
                            $scope.projectIntention.jsfDis = '开发商 ' + $scope.projectIntention.kfs;
                        } else {
                            $scope.projectIntention.kfs = '';
                        }
                        break;
                    case 'COMPLETION_YEAR':
                        $scope.projectIntention.jzjgnf = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.jzjgnfDis = $scope.projectIntention.choiceItem.meaning;
                        break;
                    case 'HOUSE_STRUCTURE':
                        $scope.projectIntention.fwjg = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.fwjgDis = $scope.projectIntention.choiceItem.meaning;
                        break;
                    case 'ROOF_TYPE':
                        $scope.projectIntention.wdlx = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.wdlxDis = $scope.projectIntention.choiceItem.meaning;
                        break;
                    case 'ROOF_STRUCTURE':
                        $scope.projectIntention.wdjg = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.wdjgDis = $scope.projectIntention.choiceItem.meaning;
                        if ($scope.projectIntention.choiceItem.code == "OTHER") {
                            $scope.projectIntention.wdjgDis = $scope.projectIntention.choiceItem.meaning;
                            ;
                            $scope.projectIntention.wdjgQt = $scope.projectIntention.choiceItem.meaning;
                        } else {
                            $scope.projectIntention.wdjgQt = '';
                        }
                        break;
                    case 'ROOF_LOAD':
                        $scope.projectIntention.wdhz = $scope.projectIntention.choiceItem.code;
                        $scope.projectIntention.wdhzDis = $scope.projectIntention.choiceItem.meaning;
                        break;
                    default:
                        return;
                }

                $lookup.clearChoiceItem();
            }
        });
    })
    .controller('TaskSurveyCtrl', function ($interval, $cordovaToast, $state, resize, $ionicHistory, $scope, $task, $stateParams, $ionicScrollDelegate, $cordovaDialogs, $ionicSlideBoxDelegate, $user, $dfHttp, $lookup, $dfCache, $loading, IMAGES, $imageUploadCache, $ionicPopup, $timeout, $dfImagePicker, $ionicActionSheet) {
        var hammerMask = document.getElementById("hammer-mask");
        var hammerBg = document.getElementById("hammer-bg");
        var hammerBox = document.getElementById("hammer-box");
        var hammerPage = document.getElementById("hammer-page");
        var imgBig = document.getElementById("image-big");

        window.initHammer(hammerMask, hammerBg, hammerBox, hammerPage, imgBig);

        $scope.useHammer = function (index, className) {
            var imagesArr = $scope[className + '_preview'],
                images = imagesArr.images.map(function (image) {
                    if (image.resource == "LOCAL") {
                        return image.imageUrl;
                    } else {
                        return image.largeImageUrl;
                    }
                });

            window.showHammer(images, index);
        }

        //$ionicHistory.clearHistory();
        $timeout(function () {
            $scope.uploadPhotoToServer = function () {
                angular.forEach(surveyImageClass, function (imageClass) {
                    //从数据库中找出图片
                    var imageCache = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, 'PROJECT', imageClass);
                    imageCache.funId = $scope.projectIntention.projectId;
                    imageCache.funName = 'PROJECT';
                    imageCache.imageClass = imageClass;
                    if (imageCache.imageStatus == 'UPLOADED' || imageCache.imageStatus == 'UPLOADING') {
                        return;
                    }
                    imageCache.imageStatus = 'SUBMIT';
                    $imageUploadCache.saveImages(imageCache);
                });
                $task.startToUploadAll();
                $cordovaToast.showShortBottom("已经开始图片上传,图片将在网络情况良好的情况下,上传到服务器");
            }

            $scope.backToTask = function () {
                var oldData = $dfCache.getObject('surveyInfo$' + $scope.projectIntention.projectId);
                var isNewInfo = false;


                for (var key in oldData) {
                    if (key == "spmsSurveyWmList" && oldData.spmsSurveyWmList) {
                        for (var i = 0; i < oldData.spmsSurveyWmList.length; i++) {

                            for (var roomKey in oldData.spmsSurveyWmList[i]) {
                                if (oldData.spmsSurveyWmList[i]['' + roomKey + ''] != $scope.projectIntention.spmsSurveyWmList[i]['' + roomKey + '']) {
                                    isNewInfo = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (key == "classList" && oldData.classList) {
                        for (var i = 0; i < oldData.classList.length; i++) {
                            if (angular.toJson(oldData.classList[i]) != angular.toJson($scope.projectIntention.classList[i])) {
                                isNewInfo = true;
                                break;
                            }
                        }
                    }

                    if (oldData["" + key + ""] != $scope.projectIntention["" + key + ""]) {
                        if (key.length > 3 && key.substring(key.length - 3, key.length) == "Dis") {

                            continue;
                        }

                        if (key == "spmsSurveyWmList" || key == "classList" || key == "surveyWmId" || key == "choiceItem") {
                            continue;
                        }
                        isNewInfo = true;
                        break;
                    }
                }

                if (oldData.projectId && !isNewInfo) {
                    $ionicHistory.goBack(-2);
                } else if (oldData.projectId) {
                    $cordovaDialogs.confirm('是否需要保存?', '勘查数据', ['保存并返回', '直接返回']).then(function (buttonIndex) {
                        if (buttonIndex == 2) {
                            //$state.go('tab.tasks',{},{reload:true});
                            //$ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
                            $ionicHistory.goBack(-2);
                        }

                        if (buttonIndex == 1) {
                            $scope.projectIntention.spmsSurveyWmList = $scope.rooms;
                            $dfCache.putObject('surveyInfo$' + $scope.projectIntention.projectId, $scope.projectIntention);
                            //$state.go('tab.tasks',{},{reload:true});
                            //$ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
                            $ionicHistory.goBack(-2);
                        }
                    });

                } else {
                    $ionicHistory.goBack(-2);
                }
            }
            $scope.submitXY = function () {
                //console.log($scope.projectIntention);
                $state.go('tab.task-position-submit', { args: $scope.projectIntention, flag: 'BasicToMap' });
            }


            resize($scope).call(function () {
                $timeout(function () {
                    if (ionic.Platform.isAndroid()) {
                        $scope.slideHeight = {
                            'height': document.body.scrollHeight - 128 + 'px'
                        };
                        $scope.slideHeightPx = document.body.scrollHeight - 128;
                    } else {
                        $scope.slideHeight = {
                            'height': document.body.scrollHeight - 128 - 20 + 'px'
                        }
                        $scope.bottomHeigth = '0px';
                        $scope.slideHeightPx = document.body.scrollHeight - 128 - 20;
                    }
                }, 1);
            });

            //勘测结果
            $scope.verdict = { 'display': '', 'basicDis': '' };

            $scope.curStyle = 0;
            $scope.curSubStyle = 0;
            $scope.showTile = false;
            $scope.showGirder = false;
            $scope.rooms = [
                {
                    "wmqj": "",
                    "wdcx": "",
                    "wmLong": "",
                    "wmWeith": "",
                    "nrqHeigth": "",
                    "wmtq": "",
                    "wmhd": "",
                    "fsfa": "",
                    "wmxz": "",
                    "bwwdlx": "",
                    'roomIndex': ""
                }
            ];

            if (ionic.Platform.isAndroid()) {
                $scope.slideHeight = {
                    'height': document.body.scrollHeight - 128 + 'px',
                };
                $scope.slideHeightPx = document.body.scrollHeight - 128;
            } else {
                $scope.slideHeight = {
                    'height': document.body.scrollHeight - 128 - 20 + 'px',
                };
                $scope.slideHeightPx = document.body.scrollHeight - 128 - 20;
            }


            $scope.navi = {
                'currentIndex': 0
            }

            $scope.projectIntention = {
                "uploaded": "",
                "customerExpectation": "",
                "customerExpectationDis": "",
                "propertyRight": "",
                "propertyRightDis": "",
                "jhjt": "",
                "jsf": "",
                "kfs": "",
                "kfsDis": "",
                "jzjgnf": "",
                "jzjgnfDis": "",
                "fwjg": "",
                "fwjgDis": "",
                "wdlx": "",
                "wdlxDis": "",
                "wdjg": "",
                "wdjgQt": "",
                "wdhz": "",
                "wdhzDis": "",
                "buildingHeight": "",
                "floors": "",
                "zwwz": "",
                "zwgd": "",
                "jhdy": "",
                "zxfs": "",
                "zxfsDis": "",
                "yydbx": "",
                "wmfld": "",
                "jxzkgrl": "",
                "nbqaz": "",
                "pdxaz": "",
                "wltx": "",
                "btpjyd": "",
                "dwyq": "",
                "dwyqQt": "",
                "dwgs": "",
                "yztgzl": "",
                "wplx": "",
                "wpccL": "",
                "wpccW": "",
                "wpdj": "",
                "wpbm": "",
                "wpzk": "",
                "bwsl": "",
                "llx": "",
                "llxQt": "",
                "lcc": "",
                "ljj": "",
                "lcd": "",
                "lbj": "",
                "sqjj": "",
                "sqhd": "",
                "remark": "",
                "surveyResult": "",
                "creationDate": "",
                "surveyEndTime": "",
                "causation": "",
                "surveyId": "",
                "projectId": "",
                "userId": "",
                "spmsSurveyWmList": [{
                    "bwwdlx": "",
                    "bwwdlxDis": "",
                    "fsfa": "",
                    "fsfaDis": "",
                    "fsfaQt": "",
                    "nrqHeigth": "",
                    "projectId": "",
                    "surveyWmId": "",
                    "wdcx": "",
                    "wmLong": "",
                    "wmWeith": "",
                    "wmhd": "",
                    "wmqj": "",
                    "wmtq": "",
                    "wmxz": "",
                    "roomIndex": ""
                }],
                "surveyWmId": []
            };

            for (var key in $stateParams.args) {
                if (key == 'remark') {
                    continue;
                }
                $scope.projectIntention['' + key + ''] = $stateParams.args['' + key + '']
            }


            $scope.forwardMap = function () {
                $state.go('tab.task-position-submit', { args: $scope.projectIntention }, { relative: '^', location: false });
            }

            $scope.showConfirm = function (item) {
                if ($scope.rooms.length > 1) {
                    $cordovaDialogs.confirm('确认删除屋面?', '删除屋面', ['取消', '确认删除']).then(function (buttonIndex) {
                        if (buttonIndex == 2) {
                            $scope.deleteRoomItem(item);
                        }
                    })

                } else {
                    $cordovaDialogs.alert('屋面数量不能少于1', '删除屋面', '确定');
                }
            };

            $scope.deleteRoomItem = function (item) {
                for (var i = 0; i < $scope.rooms.length; i++) {
                    if (item.roomIndex == $scope.rooms[i].roomIndex) {
                        $scope.rooms.splice(i, 1);
                        break;
                    }
                }
                var e = {};
                e.target = document.getElementById("subTab0");
                $scope.activeSubNav(e);
            };

            //给projectId赋值
            //$scope.projectIntention.projectId = $stateParams.taskId;

            console.log($scope.projectIntention);


            //选择图片
            $scope.choiceImage = function (imageClass) {
                $state.go('tab.task-common-photo', {
                    args: {
                        funId: $scope.projectIntention.projectId,
                        funName: 'PROJECT',
                        imageClass: imageClass
                    }
                });
            }

            $user.getCurrentUser().executeSuccess(function (user) {
                $scope.user = user;
                $scope.projectIntention.userId = user.userId;

                $scope.getCache();
                if ($scope.projectIntention.uploaded || $scope.projectIntention.uploaded === '') {
                    $task.getSurveyInfo($scope.projectIntention.userId, $scope.projectIntention.projectId).success(function (data) {
                        if (data.code == 'SUCCESS') {
                            if (data.data) {
                                $scope.rooms = data.data.spmsSurveyWmList;
                                if (!angular.isArray($scope.rooms) || $scope.rooms.length == 0) {
                                    $scope.rooms = [{
                                        "bwwdlx": "",
                                        "bwwdlxDis": "",
                                        "fsfa": "",
                                        "fsfaDis": "",
                                        "nrqHeigth": "",
                                        "projectId": "",
                                        "surveyWmId": "",
                                        "wdcx": "",
                                        "wmLong": "",
                                        "wmWeith": "",
                                        "wmhd": "",
                                        "wmqj": "",
                                        "wmtq": "",
                                        "wmxz": "",
                                        "roomIndex": ""
                                    }];
                                    data.data.spmsSurveyWmList = [{
                                        "bwwdlx": "",
                                        "bwwdlxDis": "",
                                        "fsfa": "",
                                        "fsfaDis": "",
                                        "nrqHeigth": "",
                                        "projectId": "",
                                        "surveyWmId": "",
                                        "wdcx": "",
                                        "wmLong": "",
                                        "wmWeith": "",
                                        "wmhd": "",
                                        "wmqj": "",
                                        "wmtq": "",
                                        "wmxz": "",
                                        "roomIndex": ""
                                    }];
                                }

                                $scope.setData(data.data);
                                $scope.setDis();
                                $scope.projectIntention.userId = $scope.user.userId;

                                var needReplaceImageClass = [];
                                //此处替换图片
                                angular.forEach(surveyImageClass, function (imageClass) {
                                    //获取图片
                                    var imageCache = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, 'PROJECT', imageClass);
                                    if (!imageCache.imageStatus || imageCache.imageStatus == 'UPLOADED' || imageCache.imageStatus == '') {
                                        needReplaceImageClass.push(imageClass);
                                    }
                                });
                                $task.saveNetworkImage($scope.projectIntention.projectId, data.data.classList, needReplaceImageClass);
                                $dfCache.putObject('surveyInfo$' + $scope.projectIntention.projectId, angular.copy($scope.projectIntention));
                                $scope.loadImageCount();

                            }
                        }
                    }).error(function (data) {

                    });
                } else {
                    $scope.setDis();
                }

            });

            $scope.getCache = function () {
                var data = $dfCache.getObject('surveyInfo$' + $scope.projectIntention.projectId);
                if (data.kfs) {
                    $scope.projectIntention.jsfDis = data.kfs;
                }
                if (data) {
                    $scope.rooms = data.spmsSurveyWmList;
                    if (!angular.isArray($scope.rooms) || $scope.rooms.length == 0) {
                        $scope.rooms = [{
                            "wmxz": "",
                            "wmxzDis": "",
                            "bwwdlx": "",
                            "bwwdlxDis": "",
                            "fsfa": "",
                            "fsfaDis": "",
                            "fsfaQt": "",
                            "nrqHeigth": "",
                            "projectId": "",
                            "surveyWmId": "",
                            "wdcx": "",
                            "wmLong": "",
                            "wmWeith": "",
                            "wmhd": "",
                            "wmqj": "",
                            "wmtq": "",
                            "roomIndex": ""
                        }];
                        data.spmsSurveyWmList = [{
                            "bwwdlx": "",
                            "bwwdlxDis": "",
                            "fsfa": "",
                            "fsfaDis": "",
                            "nrqHeigth": "",
                            "projectId": "",
                            "surveyWmId": "",
                            "wdcx": "",
                            "wmLong": "",
                            "wmWeith": "",
                            "wmhd": "",
                            "wmqj": "",
                            "wmtq": "",
                            "wmxz": "",
                            "roomIndex": ""
                        }];
                    }
                    $scope.setData(data);
                    $scope.projectIntention.userId = $scope.user.userId;
                }
            }
            $scope.setData = function (data) {
                for (var key in data) {
                    if (key == 'projectId' || key == 'userId') {
                        continue;
                    }
                    ;
                    $scope.projectIntention['' + key + ''] = data['' + key + ''];
                }

                if ($scope.projectIntention.surveyResult == '合适') {
                    $scope.verdict.display = "合适";
                    $scope.verdict.basicDis = "合适";
                } else if ($scope.projectIntention.surveyResult == '不合适') {
                    $scope.verdict.display = "不合适";
                    $scope.verdict.basicDis = "不合适";
                } else {
                    $scope.verdict.display = "请选择";
                    $scope.verdict.basicDis = "勘测中";
                }
            }

            $scope.setDis = function () {
                if ($scope.rooms) {
                    for (var i = 0; i < $scope.rooms.length; i++) {
                        var room = $scope.rooms[i];
                        $scope.rooms[i].roomIndex = i;

                        for (var key1 in room) {
                            if (angular.isString(room['' + key1 + ''])) {
                                $lookup.getWithLookupCode(room['' + key1 + ''], {
                                    'key': key1,
                                    'index': i
                                }).executeSuccess(function (lookup) {
                                    if (lookup.lookupCode) {
                                        $scope.rooms[lookup.options.index]['' + lookup.options.key + 'Dis'] = lookup.lookupMeaning;
                                    }
                                })
                            }
                        }
                    }
                }

                for (var key in $scope.projectIntention) {
                    if ($scope.projectIntention['' + key + '']) {

                        if (key == "jsf" && $scope.projectIntention.jsf == "OTHER") {
                            $scope.projectIntention.jsfDis = $scope.projectIntention.kfs;
                        }


                        if (key == 'wdjg' && $scope.projectIntention.wdjg == "OTHER") {
                            $scope.projectIntention.wdjgDis = $scope.projectIntention.wdjgQt;
                        }

                        if (key != 'dwyq') {
                            $lookup.getWithLookupCode($scope.projectIntention['' + key + ''], key).executeSuccess(function (lookup) {
                                if (lookup.lookupCode) {
                                    if (lookup) {
                                        $scope.projectIntention['' + lookup.options + 'Dis'] = lookup.lookupMeaning;
                                    }
                                }
                            })
                        }
                    }
                }

                if (angular.isString($scope.projectIntention.dwyq)) {
                    var codes = $scope.projectIntention.dwyq.split(",");
                    $scope.projectIntention.dwyqDis = '';

                    for (var k = 0; k < codes.length; k++) {

                        if (codes[k] == 'OTHER') {
                            $scope.projectIntention.dwyqDis += $scope.projectIntention.dwyqQt + ' ';
                        } else {
                            $lookup.getWithLookupCode(codes[k]).executeSuccess(function (lookup) {
                                if (lookup.lookupCode) {
                                    if (lookup) {
                                        $scope.projectIntention.dwyqDis += lookup.lookupMeaning + ' ';
                                    }
                                }
                            })
                        }

                    }
                }

                //此处处理瓦结构和梁结构
                if ($scope.projectIntention.wdjg == 'LJG') {
                    $scope.showGirder = true;
                } else {
                    $scope.showGirder = false;
                }
                if ($scope.projectIntention.wdlx == "SLOPE_TILED_ROOF" || $scope.projectIntention.wdlx == "COLOR_STEEL_TILE") {
                    $scope.showTile = true;
                } else {
                    $scope.showTile = false;
                }

            };


            //图片上传为什么要使用Base64 模拟form表单提交不成,safiri对js的file元素支持的不够好
            //TODO:图片上传.
            //勘察一览图片上传数据 图片状态
            var surveyImageClass = IMAGES.survey;

            //$scope.uploadSurveyPhoto

            $scope.uploadSurvey = function () {
                $loading.show('提交中');
                //提交勘查
                $scope.projectIntention.uploaded = true;
                $scope.projectIntention.spmsSurveyWmList = $scope.rooms;
                $scope.projectIntention.userId = $scope.user.userId;

                $dfHttp.post("api/survey/createOrUpdateSurvey.json", $scope.projectIntention).success(function (data) {
                    if (data.code == 'SUCCESS') {
                        $loading.showSuccess(data.msg);
                        $scope.projectIntention.surveyId = data.data.surveyId;
                        for (var i = 0; i < data.data.surveyWmId.length; i++) {
                            $scope.projectIntention.spmsSurveyWmList[i].surveyWmId = data.data.surveyWmId[i];
                            $scope.rooms[i].surveyWmId = data.data.surveyWmId[i];
                        }
                        $dfCache.putObject('surveyInfo$' + $scope.projectIntention.projectId, angular.copy($scope.projectIntention));

                        //更改图片状态为SUBMIT
                        angular.forEach(surveyImageClass, function (imageClass) {
                            //从数据库中找出图片
                            var imageCache = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, 'PROJECT', imageClass);
                            if (imageCache.imageStatus == 'UPLOADED' || imageCache.imageStatus == 'UPLOADING') {
                                return;
                            }
                            imageCache.funId = $scope.projectIntention.projectId;
                            imageCache.funName = 'PROJECT';
                            imageCache.imageClass = imageClass;
                            imageCache.imageStatus = 'SUBMIT';
                            $imageUploadCache.saveImages(imageCache);
                        });
                        //下次读取图片，应该把为UPLOADED的替换掉
                        $task.startToUploadAll();

                        $state.go('tab.tasks', {}, { reload: true });
                        $ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
                    } else {
                        $loading.showError(data.msg);
                    }
                });
            }

            $scope.saveSurvey = function (showMsg) {
                //暂存勘查
                $scope.projectIntention.uploaded = false;
                $scope.projectIntention.spmsSurveyWmList = $scope.rooms;
                $dfCache.putObject('surveyInfo$' + $scope.projectIntention.projectId, angular.copy($scope.projectIntention));
                if (showMsg) {
                    $loading.showSuccess('勘查数据已暂存');
                }
            }

            $scope.goChoice = function (type, current, tag) {
                $scope.viewTag = tag;
                $state.go('tab.task-common-choice', {
                    'args': {
                        'lookupType': type,
                        'currentCode': current
                    }
                });
            };

            $scope.goInputText = function (obj, propName) {
                $state.go('tab.task-common-textarea', {
                    args: {
                        obj: obj,
                        propName: propName
                    }
                });
            }

            $scope.goChoiceWithOther = function (type, current, otherTitle, otherHolder, isMutable) {

                $state.go('tab.task-common-choice', {
                    'args': {
                        'lookupType': type,
                        'currentCode': current,
                        'showOther': true,
                        'otherName': otherTitle,
                        'otherValue': otherHolder,
                        'isMutable': isMutable
                    }
                });
            };

            $scope.goMutableChoice = function (type, current, otherTitle, otherHolder) {

                $state.go('tab.task-mutable-choice', {
                    'args': {
                        'lookupType': type,
                        'currentCode': current,
                        'showOther': true,
                        'otherName': otherTitle,
                        'otherValue': otherHolder
                    }
                });
            };


        }, 300);

        $scope.loadImageCount = function () {
            var surveyImageClass = IMAGES.survey;

            $timeout(function () {
                // 循环遍历imaClass
                angular.forEach(surveyImageClass, function (data) {
                    switch (data) {
                        case "ROOF_SIZE":
                            $scope.ROOF_SIZE = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.ROOF_SIZE_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "JHJTT_KC":
                            $scope.JHJTT_KC = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.JHJTT_KC_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "FWZST":
                            $scope.FWZST = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.FWZST_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_PANORAMA":
                            $scope.ROOF_PANORAMA = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.ROOF_PANORAMA_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_EAST":
                            $scope.ROOF_EAST = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.ROOF_EAST_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_SOUTH":
                            $scope.ROOF_SOUTH = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.ROOF_SOUTH_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_WEST":
                            $scope.ROOF_WEST = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.ROOF_WEST_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "TILE_PHOTO":
                            $scope.TILE_PHOTO = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.TILE_PHOTO_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "XWJGZP":
                            $scope.XWJGZP = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.XWJGZP_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "LJGZP":
                            $scope.LJGZP = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.LJGZP_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "YZTGZLT":
                            $scope.YZTGZLT = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.YZTGZLT_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "NBQAZWZ":
                            $scope.NBQAZWZ = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.NBQAZWZ_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "PDXAZWZ":
                            $scope.PDXAZWZ = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.PDXAZWZ_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "BWDWZ":
                            $scope.BWDWZ = $imageUploadCache.getImagesCount($scope.projectIntention.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                            $scope.BWDWZ_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        default:
                            break;
                    }
                });
            }, 1);
        };

        $scope.goInputText = function (obj, propName) {
            $state.go('tab.task-common-textarea', {
                args: {
                    obj: obj,
                    propName: propName
                }
            });
        }

        $scope.$on('$ionicView.beforeLeave', function () {
            $interval.cancel($scope.loadImageInterval);
        });

        $scope.$on('$ionicView.afterEnter', function () {
            //获取constant中的IMAGES.survey
            // if($scope.projectIntention.projectId) {
            //   $scope.loadImageInterval = $interval(function(){
            //     $scope.loadImageCount();
            //   },300);
            // }

            $timeout(function () {
                if ($scope.projectIntention.projectId) {
                    $scope.loadImageInterval = $interval(function () {
                        $scope.loadImageCount();
                    }, 300);
                }
            }, 300);

            $timeout(function () {
                //获取指定参数,如果不存在就不处理
                $scope.projectIntention.choiceItem = $lookup.getChoiceItem();
                if ($scope.projectIntention.choiceItem) {
                    switch ($scope.projectIntention.choiceItem.type) {
                        case 'CUSTOMER_EXPECTATION':
                            $scope.projectIntention.customerExpectation = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.customerExpectationDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'PROPERTY_RIGHT':
                            $scope.projectIntention.propertyRight = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.propertyRightDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'NETWORK_CONDITIONS':
                            $scope.projectIntention.wltx = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.wltxDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'CONSTRUCTION':
                            $scope.projectIntention.jsf = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.jsfDis = $scope.projectIntention.choiceItem.meaning;
                            //$scope.projectIntention.kfs = $scope.projectIntention.choiceItem.meaning;

                            if ($scope.projectIntention.jsf == 'OTHER') {
                                $scope.projectIntention.kfs = $scope.projectIntention.choiceItem.meaning;
                                $scope.projectIntention.jsfDis = $scope.projectIntention.kfs;
                            } else {
                                $scope.projectIntention.kfs = '';
                            }
                            break;
                        case 'COMPLETION_YEAR':
                            $scope.projectIntention.jzjgnf = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.jzjgnfDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'HOUSE_STRUCTURE':
                            $scope.projectIntention.fwjg = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.fwjgDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'ROOF_SHAPE':
                            $scope.rooms[$scope.curSubStyle].wmxz = $scope.projectIntention.choiceItem.code;
                            $scope.rooms[$scope.curSubStyle].wmxzDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'ROOF_TYPE':
                            var tag = $scope.viewTag;
                            if (tag == 'bwwdlx') {
                                $scope.rooms[$scope.curSubStyle].bwwdlx = $scope.projectIntention.choiceItem.code;
                                $scope.rooms[$scope.curSubStyle].bwwdlxDis = $scope.projectIntention.choiceItem.meaning;
                            } else {
                                $scope.projectIntention.wdlx = $scope.projectIntention.choiceItem.code;
                                $scope.projectIntention.wdlxDis = $scope.projectIntention.choiceItem.meaning;
                                var code = $scope.projectIntention.choiceItem.code;
                                if (code == "SLOPE_TILED_ROOF" || code == "COLOR_STEEL_TILE") {
                                    $scope.showTile = true;
                                } else {
                                    $scope.showTile = false;
                                }
                            }
                            break;
                        case 'ROOF_STRUCTURE':
                            $scope.projectIntention.wdjg = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.wdjgDis = $scope.projectIntention.choiceItem.meaning;
                            var code = $scope.projectIntention.choiceItem.code;

                            if (code != "OTHER") {
                                $scope.projectIntention.wdjgQt = "";
                            } else {
                                $scope.projectIntention.wdjgQt = $scope.projectIntention.wdjgDis;
                            }
                            if ($scope.projectIntention.llx != "OTHER") {
                                $scope.projectIntention.llxQt = "";
                            } else {
                                $scope.projectIntention.llxQt = $scope.projectIntention.llxDis;
                            }
                            if (code == "LJG") {
                                $scope.showGirder = true;
                            } else {
                                $scope.showGirder = false;
                            }
                            break;
                        case 'ROOF_LOAD':
                            $scope.projectIntention.wdhz = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.wdhzDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'BEAM_TYPE':
                            $scope.projectIntention.llx = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.llxDis = $scope.projectIntention.choiceItem.meaning;

                            if ($scope.projectIntention.llx != "OTHER") {
                                $scope.projectIntention.llxQt = "";
                            } else {
                                $scope.projectIntention.llxQt = $scope.projectIntention.llxDis;
                            }
                            break;

                        case 'INDOOR_POWER_SOURCE':
                            $scope.projectIntention.jhdy = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.jhdyDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'LINE_STYLE':
                            $scope.projectIntention.zxfs = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.zxfsDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'ROOFING_ANTI_RADER_BELT':
                            $scope.projectIntention.wmfld = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.wmfldDis = $scope.projectIntention.choiceItem.meaning;
                            break;
                        case 'DWYQ':
                            $scope.projectIntention.dwyq = $scope.projectIntention.choiceItem.code;
                            $scope.projectIntention.dwyqDis = $scope.projectIntention.choiceItem.meaning;

                            var codes = $scope.projectIntention.dwyq.split(",");
                            var diss = $scope.projectIntention.dwyqDis.split(" ");
                            if (codes[codes.length - 1] != "OTHER") {
                                $scope.projectIntention.dwyqQt = "";
                            } else {
                                $scope.projectIntention.dwyqQt = diss[diss.length - 1];
                            }
                            break;
                        case 'WATERPROOF_PLAN':
                            $scope.rooms[$scope.curSubStyle].fsfa = $scope.projectIntention.choiceItem.code;
                            $scope.rooms[$scope.curSubStyle].fsfaDis = $scope.projectIntention.choiceItem.meaning;

                            if ($scope.rooms[$scope.curSubStyle].fsfa != "OTHER") {
                                $scope.rooms[$scope.curSubStyle].fsfaQt = "";
                            } else {
                                $scope.rooms[$scope.curSubStyle].fsfaQt = $scope.rooms[$scope.curSubStyle].fsfaDis;
                            }
                            break;
                        default:
                            return;
                    }
                    $lookup.clearChoiceItem();
                }
            }, 2);
        });

        $scope.goPhoto = function (type) {
            $state.go('tab.task-common-photo', {
                "args": {
                    "funId": $scope.projectIntention.projectId,
                    "funName": "PROJECT",
                    "imageClass": type
                }
            });
        }

        $scope.finishPhoto = function () {

        }

        $scope.addRoom = function () {
            var newRoom = {
                "bwwdlx": "",
                "bwwdlxDis": "",
                "fsfa": "",
                "fsfaDis": "",
                "nrqHeigth": "",
                "projectId": "",
                "surveyWmId": "",
                "wdcx": "",
                "wmLong": "",
                "wmWeith": "",
                "wmhd": "",
                "wmqj": "",
                "wmtq": "",
                "wmxz": "",
                "x": ""
            };
            newRoom.roomIndex = $scope.rooms.length;
            $scope.rooms.push(newRoom);
            //触发activeSubNav让slide-box正常显示
            setTimeout(function () {
                var e = {};
                e.target = document.getElementById("subTab" + ($scope.rooms.length - 1));
                $scope.activeSubNav(e);
                $scope.activeSubSlide($scope.rooms.length - 1);
            }, 200);

        }

        //TODO:$$$$$$

        //点击事件
        $scope.activeNav = function ($event) {
            $scope.saveSurvey(false);
            var currentElem = $event.target;
            var parentElem = document.getElementsByClassName("nav-scroll")[0];
            var index = 0;
            for (var i = 0; i < parentElem.children.length; i++) {
                if (currentElem == parentElem.children[i]) {
                    $scope.curStyle = i;
                    $scope.navi.currentIndex = i;
                    currentElem.className = 'active';
                    $scope.vm['lazyLoad' + (i + 1)] = true;
                } else {
                    parentElem.children[i].className = "";
                    $scope.vm['lazyLoad' + (i + 1)] = false;
                }
                var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-box');
                if ($scope.curStyle < sildeBox.slidesCount()) {
                    sildeBox.slide($scope.curStyle, 500);
                    sildeBox.update();
                }
            }

            if ($scope.curStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTo(($scope.curStyle - 2) * 80, 0, true);
            }
            if ($scope.curStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTop(true);
            }


            //当索引等于照片一览的值时，获取缓存中的照片src
            if ($scope.curStyle == 6) {

                $timeout(function () {
                    var image = document.getElementById("addJHJTT_KC");
                    $scope.photoHeight = image.offsetWidth;
                }, 50);

                var previewImgClass = IMAGES.survey;

                // 循环遍历imaClass
                angular.forEach(previewImgClass, function (data) {
                    // $scope.photoHeight = document.getElementById("add"+data).offsetWidth;
                    switch (data) {
                        case "JHJTT_KC":
                            $scope.JHJTT_KC_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "FWZST":
                            $scope.FWZST_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_PANORAMA":
                            $scope.ROOF_PANORAMA_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_EAST":
                            $scope.ROOF_EAST_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_WEST":
                            $scope.ROOF_WEST_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "ROOF_SOUTH":
                            $scope.ROOF_SOUTH_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "TILE_PHOTO":
                            $scope.TILE_PHOTO_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "XWJGZP":
                            $scope.XWJGZP_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "LJGZP":
                            $scope.LJGZP_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "YZTGZLT":
                            $scope.YZTGZLT_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "NBQAZWZ":
                            $scope.NBQAZWZ_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "PDXAZWZ":
                            $scope.PDXAZWZ_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        case "BWDWZ":
                            $scope.BWDWZ_preview = $imageUploadCache.getImagesByParams($scope.projectIntention.projectId, "PROJECT", data);
                            break;
                        default:
                            break;
                    }
                })
            }

        }

        //是否合格建设
        $scope.isVerdict = function () {
            var verdictSheet = $ionicActionSheet.show({
                buttons: [
                    { text: "合适" },
                    { text: "不合适" }
                ],
                cancelText: "取消",
                cancel: function () {
                    verdictSheet();
                },
                buttonClicked: function (index) {
                    $user.getCurrentUser().executeSuccess(function (user) {
                        if (index == 0) {
                            $scope.verdict.display = '合适';
                            $scope.verdict.basicDis = '合适';
                            $scope.projectIntention.surveyResult = '合适';
                        }

                        if (index == 1) {
                            $scope.verdict.display = '不合适';
                            $scope.verdict.basicDis = '不合适';
                            $scope.projectIntention.surveyResult = '不合适';
                        }

                        user.isVerdict = $scope.verdict.verdict;
                        $user.saveUserWithoutAutoLogin(user);

                        verdictSheet();
                    })
                }
            });
        }

        $scope.activeSubNav = function ($event) {
            var currentElem = $event.target;
            var parentElem = document.getElementsByClassName("nav-sub-scroll")[0];
            var index = 0;
            for (var i = 0; i < parentElem.children.length; i++) {
                if (currentElem == parentElem.children[i]) {
                    $scope.curSubStyle = i;
                    currentElem.className = 'active';
                } else {
                    parentElem.children[i].className = "";
                }
                var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-sub-box');
                if ($scope.curSubStyle < sildeBox.slidesCount()) {
                    sildeBox.slide($scope.curSubStyle, 500);
                    sildeBox.update();
                }
            }
            if ($scope.curSubStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-sub-scroll').scrollTo(($scope.curSubStyle - 2) * 80, 0, true);
            }
            if ($scope.curSubStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-sub-scroll').scrollTop(true);
            }
        }

        $scope.activeSlide = function (index) {
            $scope.navi.currentIndex = index;
            var parentElem = document.getElementsByClassName("nav-scroll")[0];
            for (var i = 0; i < parentElem.children.length; i++) {
                if (index == i) {
                    $scope.curStyle = i;
                    var currentElem = parentElem.children[i];
                    currentElem.className = 'active';
                    //console.log(i);
                } else {
                    parentElem.children[i].className = "";
                }
            }
            var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-box');
            sildeBox.slide($scope.curStyle, 500);
            sildeBox.update();
            if ($scope.curStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTo(($scope.curStyle - 2) * 80, 0, true);
            }
            if ($scope.curStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTop(true);
            }

            if ($scope.curStyle == 2) {
                //进入勘查-房屋页面后触发activeSubNav让slide-box正确显示
                setTimeout(function () {

                    var e = {};
                    e.target = document.getElementById("subTab0");
                    $scope.activeSubNav(e);
                }, 200);
            }


        }

        $scope.activeSubSlide = function (index) {
            var parentElem = document.getElementsByClassName("nav-sub-scroll")[0];
            for (var i = 0; i < parentElem.children.length; i++) {
                if (index == i) {
                    $scope.curSubStyle = i;
                    var currentElem = parentElem.children[i];
                    currentElem.className = 'active';
                    //console.log(i);
                } else {
                    parentElem.children[i].className = "";
                }
            }
            var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-sub-box');
            sildeBox.slide($scope.curSubStyle, 500);
            sildeBox.enableSlide(false);
            sildeBox.update();
            if ($scope.curSubStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-sub-scroll').scrollTo(($scope.curSubStyle - 2) * 80, 0, true);
            }
            if ($scope.curSubStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-sub-scroll').scrollTop(true);
            }
        }

        $scope.call = function (PhoneNumber) {
            $cordovaDialogs.confirm('确认拨打' + PhoneNumber + '?', '拨打电话', ['取消', '拨打']).then(function (buttonIndex) {
                if (buttonIndex == 2) {
                    window.open("tel:" + PhoneNumber);
                }
            })
        }


        $scope.vm = {};
        $scope.vm.lazyLoad0 = false;
        $scope.vm.lazyLoad1 = false;
        $scope.vm.lazyLoad2 = false;
        $scope.vm.lazyLoad3 = false;
        $scope.vm.lazyLoad4 = false;
        $scope.vm.lazyLoad5 = false;


        $scope.vm.onTouchThis = function ($event) {
            //console.log($event);
            $ionicSlideBoxDelegate.enableSlide(false);
            $ionicSlideBoxDelegate.$getByHandle('slide-box').enableSlide(false);
        };

        $scope.vm.onDragThis = function ($event) {
            //console.log($event);
            $ionicSlideBoxDelegate.$getByHandle('slide-box').enableSlide(true);
        };


        (function () {
            $timeout(function () {
                $scope.vm.lazyLoad0 = true;
            }, 300)
        })();
        (function () {
            $timeout(function () {
                $scope.vm.lazyLoad1 = true;
            }, 600)
        })();
        (function () {
            $timeout(function () {
                $scope.vm.lazyLoad2 = true;
            }, 900)
        })();
        (function () {
            $timeout(function () {
                $scope.vm.lazyLoad3 = true;
            }, 1200)
        })();
        (function () {
            $timeout(function () {
                $scope.vm.lazyLoad4 = true;
            }, 1500)
        })();
        (function () {
            $timeout(function () {
                $scope.vm.lazyLoad5 = true;
            }, 1800)
        })();

        // 监控数据库中,图片的变化。2s 监控一次
        $scope.listenPicChange = function () {

        }

    })

    .controller('MutableChoiceCtrl', function ($rootScope, $cordovaDialogs, $scope, $lookup, $stateParams, $ionicHistory) {
        var args = $stateParams.args;
        $scope.item = { type: '', code: '', meaning: '' };
        $scope.input = { 'otherValue': '' };
        $scope.item.type = args.lookupType;

        $lookup.getWithlookupType(args.lookupType).executeSuccess(function (data) {
            $scope.choiceList = data;
            $scope.selecteds = [];
            var codes = args.currentCode.split(",");
            for (var i = 0; i < $scope.choiceList.length; i++) {
                var meaning = $scope.choiceList[i];
                $scope.selecteds.push(false);

                for (var j = 0; j < codes.length; j++) {
                    if (meaning.lookupCode == codes[j]) {
                        $scope.selecteds[i] = true;
                    }
                }

            }
            $scope.selecteds[$scope.choiceList.length] = false;
            $scope.showOther = args.showOther;
            $scope.otherName = args.otherName;
            $scope.input.otherValue = args.otherValue;

            if (args.otherValue.length > 0) {
                $scope.currentIndex = $scope.choiceList.length;
                $scope.selecteds[$scope.selecteds.length - 1] = true;
            }
            //})
        });

        $scope.choiceItem = function (index) {
            $scope.selecteds[index] = !$scope.selecteds[index];
            if (index == $scope.selecteds.length - 1 && !$scope.selecteds[index]) {

            }
        }

        $scope.finishChoice = function () {


            for (var i = 0; i < $scope.selecteds.length - 1; i++) {
                if ($scope.selecteds[i]) {
                    var meaning = $scope.choiceList[i];
                    $scope.item.meaning += (meaning.lookupMeaning + " ");
                    $scope.item.code += (meaning.lookupCode + ",");
                }
            }

            if ($scope.selecteds[$scope.selecteds.length - 1]) {
                $scope.item.meaning += ($scope.input.otherValue + " ");
                $scope.item.code += "OTHER,";
            }

            $scope.item.meaning = $scope.item.meaning.substring(0, $scope.item.meaning.length - 1);
            $scope.item.code = $scope.item.code.substring(0, $scope.item.code.length - 1);

            $lookup.sureChoiceItem($scope.item);
            $ionicHistory.goBack();
        }
    })

    .controller('CommonChoiceCtrl', function ($rootScope, $cordovaDialogs, $scope, $lookup, $stateParams, $ionicHistory) {
        var args = $stateParams.args;
        $scope.item = {};
        $scope.input = { 'otherValue': '' };
        $scope.item.type = args.lookupType;
        $lookup.getWithlookupType(args.lookupType).executeSuccess(function (data) {
            $scope.choiceList = data;
            //angular.forEach($scope.choiceList,function(lookupMeaning){
            $scope.currentIndex = -1;
            for (var i = 0; i < $scope.choiceList.length; i++) {
                var meaning = $scope.choiceList[i];
                if (meaning.lookupCode == args.currentCode) {
                    $scope.currentIndex = i;
                    $scope.item.meaning = meaning.lookupMeaning;
                    $scope.item.code = meaning.lookupCode;
                    break;
                }
            }
            $scope.showOther = args.showOther;
            $scope.otherName = args.otherName;
            $scope.input.otherValue = args.otherValue;

            if (args.showOther && $scope.currentIndex == -1 && args.currentCode == 'OTHER') {
                $scope.currentIndex = $scope.choiceList.length;
                $scope.item.code = 'OTHER';
                $scope.item.meaning = $scope.input.otherValue;
            }
            //})
        });

        $scope.choiceItem = function (index) {
            if (index < $scope.choiceList.length) {
                var meaning = $scope.choiceList[index];
                $scope.currentIndex = index;
                //$scope.item.meaning = meaning.lookupName ;
                //$scope.item.code = meaning.lookupCode ;
                $scope.finishChoice();
            } else {
                $scope.currentIndex = $scope.choiceList.length;
                //$scope.item.code = 'OTHER';
                //$scope.item.meaning = $scope.otherValue ;
            }

        }

        $scope.finishChoice = function () {
            if ($scope.currentIndex < 0) {
                $ionicHistory.goBack();
                return;
            }
            if ($scope.currentIndex < $scope.choiceList.length) {
                var meaning = $scope.choiceList[$scope.currentIndex];
                $scope.item.meaning = meaning.lookupMeaning;
                $scope.item.code = meaning.lookupCode;
            } else {
                $scope.item.code = 'OTHER';
                if ($scope.input.otherValue == "") {
                    $cordovaDialogs.alert('请完善信息!', '提示', '确认');
                    return;
                } else {
                    var otherValue = $scope.input.otherValue;
                    $scope.item.meaning = $scope.input.otherValue;
                }
            }
            $lookup.sureChoiceItem($scope.item);
            $ionicHistory.goBack();
        }
    })

    // 文本
    .controller("CommonTextareaCtrl", function ($scope, $stateParams, $ionicHistory, $loading, $cordovaDialogs, $log) {
        var propName = $stateParams.args.propName;

        $scope.vm = {
            input: eval("$stateParams.args.obj." + propName),
            disabled: $stateParams.args.isDisabled
        };

        $scope.finish = function () {
            if (angular.isUndefined($scope.vm.input) || $scope.vm.input == "") {
                $loading.showError("请输入文本！");
            } else {
                eval("$stateParams.args.obj." + propName + "=$scope.vm.input");
                $ionicHistory.goBack();
            }
        }

        $scope.back = function () {
            if (eval("$stateParams.args.obj." + propName) != $scope.vm.input) {
                $cordovaDialogs.confirm('数据未保存,确定要返回吗?', '', ['保存并返回', '直接返回']).then(function (buttonIndex) {
                    if (buttonIndex == 1) {
                        $scope.finish();
                    } else {
                        $ionicHistory.goBack();
                    }
                });
            } else {
                $ionicHistory.goBack();
            }
        }
    })

    //lookupType: "CUSTOMER_EXPECTATION", currentCode: "QITA", qitaName: "其他", qitaValue: "其他值"
    .controller('CommonPhotoCtrl', function ($imageUploadCache, $cordovaDialogs, $timeout, $rootScope, $scope, $lookup, $stateParams, $ionicHistory, $dfImagePicker, $cordovaFile, $dfHttp) {

        $scope.params = $stateParams.args;
        $scope.disable = $stateParams.disable;

        if (!$scope.params.invalidUuids) {
            $scope.params.invalidUuids = [];
        }

        var imagesTemp = [];
        angular.forEach($scope.params.netImages, function (netImage) {
            var image = {};
            image.imageUrl = netImage.middleImageUrl;
            image.largeImageUrl = netImage.largeImageUrl;
            image.smallImageUrl = netImage.smallImageUrl;
            image.uuid = netImage.uuid;
            image.status = 'NEW';
            image.resource = 'NETWORK';

            imagesTemp.push(image);
        });

        var cacheParams = $imageUploadCache.getImagesByParams($scope.params.funId, $scope.params.funName, $scope.params.imageClass);

        if (!cacheParams.images) {
            $scope.params.images = [];
        } else {
            $scope.params.images = cacheParams.images;
        }
        if ($scope.params.images.length == 0) {
            $scope.params.images = imagesTemp;
        }

        $scope.addHidden = true;
        //$scope.photosArray = [];
        //$scope.photoDatasArray = [] ;
        var img = document.getElementById('commonPhotoAdd');
        $scope.photoHeight = img.offsetWidth;

        $scope.$watch($scope.params.images, function (value) {
            if ($scope.params.images.length > 8) {
                $scope.addHidden = true;
            } else {
                $scope.addHidden = false;
            }
        });

        $scope.addPhoto = function () {
            $dfImagePicker.getImageList({ maxImages: (9 - $scope.params.images.length) }).success(function (pickImages) {
                if (pickImages) {
                    angular.forEach(pickImages, function (pickImage) {
                        $timeout(function () {
                            var cacheImage = {};

                            cacheImage.status = 'NEW';
                            cacheImage.imageUrl = pickImage;
                            cacheImage.resource = 'LOCAL';

                            $scope.params.images.push(cacheImage);
                        }, 1);
                    });
                }
              $scope.params.imageStatus = 'SAVED';
              $imageUploadCache.saveImages($scope.params);
            }).error(function (data) {
                console.log(data);
            });
        }

        //$scope.uploadPhoto = function () {
        //    $scope.params.imageStatus = 'SAVED';
        //    $imageUploadCache.saveImages($scope.params);
        //    $ionicHistory.goBack();
        //}

        $scope.deletePhoto = function (index) {
            var image = $scope.params.images[index];
            if (image.resource == 'NETWORK') {
                $scope.params.invalidUuids.push(image.uuid);
            }
            $scope.params.images.splice(index, 1);
          $scope.params.imageStatus = 'SAVED';
          $imageUploadCache.saveImages($scope.params);
        }

        var hammerMask = document.getElementById("hammer-mask");
        var hammerBg = document.getElementById("hammer-bg");
        var hammerBox = document.getElementById("hammer-box");
        var hammerPage = document.getElementById("hammer-page");
        var imgBig = document.getElementById("image-big");

        window.initHammer(hammerMask, hammerBg, hammerBox, hammerPage, imgBig);

        $scope.useHammer = function (index, className) {
            var images = [];

            $scope.params.images.forEach(function (item) {
                if (item.resource == 'LOCAL') {
                    images.push(item.imageUrl);
                } else {
                    images.push(item.largeImageUrl);
                }
            });
            window.showHammer(images, index);
        }

    })

    .controller('DesignChoiceCtrl', function ($rootScope, $cordovaDialogs, $scope, $stateParams, $ionicHistory, $dfBoradcast) {

        var args = $stateParams.args;
        $scope.items = {};
        $scope.input = { 'otherValue': '' };
        $scope.selecteds = [];
        $scope.selectedItem = {};
        $scope.items = args.items;
        if (args.haveCancel) {
            $scope.items.push({ 'category2': '逆变器', 'itemDesc': '取消', 'itemCode': 'cancel', 'itemName': '取消' });
        }
        if (args.selecteds) {
            $scope.selecteds = args.selecteds;
        }

        $scope.currentIndex = -1;
        for (var i = 0; i <= args.items.length; i++) {
            if (i < args.items.length && args.dbTag == args.items[i].itemCode) {
                $scope.currentIndex = i;
                break;
            }
            if (i == args.items.length && args.dbTag) {
                $scope.currentIndex = i;
                $scope.input.otherValue = parseInt(args.dbTag);
            }
        }

        $scope.sets = { 'showOther': false };
        $scope.sets.rightWord = args.rightWord;
        $scope.sets.category2 = $scope.items[0].category2;
        if (args.showOther) {
            $scope.sets.showOther = args.showOther;
        }

        $scope.choiceItem = function (index) {
            if (index < $scope.items.length) {
                $scope.items[index].index = index;
                $scope.selecteds = [];
                $scope.selecteds.push($scope.items[index]);
                $scope.currentIndex = index;
                $scope.finishChoice();
            } else {
                //其它
                $scope.currentIndex = $scope.items.length;
            }
        }

        $scope.finishChoice = function () {
            if ($scope.currentIndex < 0) {
                $ionicHistory.goBack();
                return;
            }
            if ($scope.currentIndex < $scope.items.length) {
                var item = $scope.items[$scope.currentIndex];
                $scope.selectedItem = item;
            } else {
                $scope.selectedItem.itemCode = 'OTHER';
                $scope.selectedItem.category2 = $scope.sets.category2;
                $scope.selectedItem.itemDesc = $scope.input.otherValue + $scope.sets.rightWord;
            }
            $scope.selectedItem.position = args.position;

            $dfBoradcast.sendBoradcastOnce('designSelected', $scope.selectedItem);
            $ionicHistory.goBack();
        }

    })

    .controller('AssignedChoiceCtrl', function ($rootScope, $loading, $dfHttp, $timeout, $cordovaDialogs, $scope, $stateParams, $ionicHistory, $dfBoradcast, modalsService) {

        var args = $stateParams.args;
        $scope.items = {};
        $scope.selecteds = [];
        $scope.selectedItem = {};
        $scope.items = args.items;
        $scope.vm = { filterTop: 44, search: '', choiceFilter: '', hasFilter: false, regionDesc: '全部服务商', regionCode: '' };
        if (args.selecteds) {
            $scope.selecteds = args.selecteds;
        }

        if (ionic.Platform.isIOS()) {
            $scope.vm.filterTop = 64;
        }

        $scope.goChoiceWithRegion = function () {
            modalsService.choiceCity({
                events: {
                    ok: 'date-modal:ok',
                    cancel: 'date-modal:cancel'
                },
                haveAll: true
            });
        };

        $scope.cancelFilter = function () {
            $scope.items = args.items;
            $scope.vm.regionDesc = "全部服务商";
            $scope.vm.hasFilter = false;
            $scope.currentIndex = -1;
            for (var i = 0; i <= args.items.length; i++) {
                if (i < args.items.length && args.dbTag == args.items[i].providerName) {
                    $scope.currentIndex = i;
                    break;
                }
                if (i == args.items.length && args.dbTag) {
                    $scope.currentIndex = i;
                }
            }
        }

        $scope.$on("date-modal:ok", function (event, data) {
            $timeout(function () {
                $scope.vm.regionDesc = data.pro.provinceName;

                if (data.city.cityName != '全部') {
                    $scope.vm.regionDesc += ' ' + data.city.cityName;
                }
                if (data.town.regionName != '全部') {
                    $scope.vm.regionDesc += ' ' + data.town.regionName;
                }

                $scope.vm.regionCode = data.town.regionCode;
                if (data.town.regionName == "全部") {
                    $scope.vm.regionCode = data.city.cityCode;
                }
                if (data.city.cityName == "全部") {
                    $scope.vm.regionCode = data.pro.provinceCode;
                }

                $loading.show('正在获取服务商');
                if ($scope.vm.regionCode) {
                    $dfHttp.get('api/others/getQueryProvider.json', {
                        'regionCode': $scope.vm.regionCode,
                        flag: '',
                        KeyWords: ''
                    }).success(function (data) {
                        if (data.code == "SUCCESS") {
                            $loading.hide();
                            $scope.vm.hasFilter = true;
                            $scope.items = data.data;

                            $scope.currentIndex = -1;
                            for (var i = 0; i <= $scope.items.length; i++) {
                                if (i < $scope.items.length && args.dbTag == $scope.items[i].providerName) {
                                    $scope.currentIndex = i;
                                    break;
                                }
                                if (i == $scope.items.length && args.dbTag) {
                                    $scope.currentIndex = i;
                                }
                            }

                        } else {
                            $loading.showError(data.msg);
                        }
                    }).error(function () {

                    })
                }


            }, 1);
        });

        $scope.currentIndex = -1;
        for (var i = 0; i <= args.items.length; i++) {
            if (i < args.items.length && args.dbTag == args.items[i].providerName) {
                $scope.currentIndex = i;
                break;
            }
            if (i == args.items.length && args.dbTag) {
                $scope.currentIndex = i;
            }
        }

        $scope.choiceItem = function (index) {
            if (index < $scope.items.length) {
                $scope.items[index].index = index;
                $scope.selecteds = [];
                $scope.selecteds.push($scope.items[index]);
                $scope.currentIndex = index;
                $scope.finishChoice();
            } else {
                //其它
                $scope.currentIndex = $scope.items.length;
            }
        }

        $scope.finishChoice = function () {
            if ($scope.currentIndex < 0) {
                $ionicHistory.goBack();
                return;
            }
            var item = $scope.items[$scope.currentIndex];
            $scope.selectedItem = item;

            $dfBoradcast.sendBoradcastOnce('assignedSelected', $scope.selectedItem);
            $ionicHistory.goBack();
        }


    })

    .controller('AutocalCtrl', function ($scope, $task, $cordovaDialogs, $stateParams, $state, $lookup, $timeout) {
        $scope.pic = {
            'rowArr': [],
            'rowNumArr': [],
            'wid': '',
            'hei': ''
        };
        $scope.projectAutocal = {
            'layoutDirection': '',
            'layoutDirectionDis': '',
            'layoutAngle': '',
            'layoutAngleDis': '',
            'num': '',
            'choiceItem': {}
        };

        $scope.goChoice = function (type, current) {
            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current
                }
            });
        };

        $scope.autoCalSets = {
            'sunHeightAngle': 0,
            'sunDirectionAngle': 0,
            'frontSpacing': 0,
            'eastSpacing': 0,
            'componentShadow': 0,
            'sumLong': 0,
            'nrqFrontSpacing': 0,
            'nrqEastSpacing': 0,
            'nrqHeight': 0,
            'hourAngle': 45,
            'componentAngle': 0,
            'long': 0,
            'width': 0,
            'latitude': 0,
            'wmLong': 0,
            'wmWidth': 0,
            'useLong': 0,
            'useWidth': 0,
            'row': 0,
            'rowNum': 0,
            'hxNum': 0,
            'zxNum': 0,
            "showPic": true
        };

        if ($stateParams.wmInfo.ableLong) {
            $scope.autoCalSets.wmLong = $stateParams.wmInfo.ableLong;
            $scope.autoCalSets.wmWidth = $stateParams.wmInfo.ableWeith;
            $scope.projectAutocal.layoutAngle = $stateParams.wmInfo.azqj;
            $scope.projectAutocal.layoutAngleDis = $lookup.getWithLookupCode($scope.projectAutocal.layoutAngle).$$state.value.lookupMeaning;
        } else {
            $scope.autoCalSets.wmLong = $stateParams.wmInfo.wmLong;
            $scope.autoCalSets.wmWidth = $stateParams.wmInfo.wmWeith;
        }

        if ($scope.projectAutocal.layoutAngle == '') {
            $scope.projectAutocal.layoutAngle = 'DIP25';
            $scope.projectAutocal.layoutAngleDis = '25';
            $scope.autoCalSets.componentAngle = 25;
        } else {
            $scope.projectAutocal.layoutAngleDis = $scope.projectAutocal.layoutAngle.substring(3, $scope.projectAutocal.layoutAngle.length);
            $scope.autoCalSets.componentAngle = parseInt($scope.projectAutocal.layoutAngleDis);
        }

        $scope.autoCalSets.nrqHeight = $stateParams.wmInfo.nrqHeigth;
        $scope.autoCalSets.latitude = $stateParams.args.latitude;

        $scope.calculates = function () {
            $scope.autoCalSets.sunHeightAngle = $task.autocalSunHeightAngle($scope.autoCalSets.latitude, $scope.autoCalSets.hourAngle);
            $scope.autoCalSets.sunDirectionAngle = $task.autocalSunDirectionAngle($scope.autoCalSets.sunHeightAngle, $scope.autoCalSets.hourAngle);
            $scope.autoCalSets.frontSpacing = $task.autocalFrontSpacing($scope.autoCalSets.width, $scope.autoCalSets.componentAngle, $scope.autoCalSets.sunHeightAngle, $scope.autoCalSets.sunDirectionAngle);
            $scope.autoCalSets.eastSpacing = $task.autocalEastSpacing($scope.autoCalSets.width, $scope.autoCalSets.componentAngle, $scope.autoCalSets.sunHeightAngle, $scope.autoCalSets.sunDirectionAngle);
            $scope.autoCalSets.componentShadow = $task.autocalComponentShadow($scope.autoCalSets.width, $scope.autoCalSets.componentAngle);
            $scope.autoCalSets.sumLong = $task.autocalSumLong($scope.autoCalSets.frontSpacing, $scope.autoCalSets.componentShadow);
            $scope.autoCalSets.nrqFrontSpacing = $task.autocalFrontSpacing($scope.autoCalSets.nrqHeight, 90, $scope.autoCalSets.sunHeightAngle, $scope.autoCalSets.sunDirectionAngle);
            $scope.autoCalSets.nrqEastSpacing = $task.autocalEastSpacing($scope.autoCalSets.nrqHeight, 90, $scope.autoCalSets.sunHeightAngle, $scope.autoCalSets.sunDirectionAngle);
            $scope.autoCalSets.useLong = $scope.autoCalSets.wmLong - $scope.autoCalSets.nrqFrontSpacing;
            $scope.autoCalSets.useWidth = $scope.autoCalSets.wmWidth - $scope.autoCalSets.nrqEastSpacing * 2;
        }
        $scope.calcuNum = function () {
            $scope.autoCalSets.row = parseInt($scope.autoCalSets.useWidth / $scope.autoCalSets.sumLong);
            $scope.autoCalSets.rowNum = parseInt($scope.autoCalSets.useLong / $scope.autoCalSets.long);
            var num = $scope.autoCalSets.rowNum * $scope.autoCalSets.row;
            $scope.pic.rowArr = [];
            $scope.pic.rowNumArr = [];
            for (var i = 0; i < $scope.autoCalSets.row; i++) {
                $scope.pic.rowArr.push(i);
            }
            for (var i = 0; i < $scope.autoCalSets.rowNum; i++) {
                $scope.pic.rowNumArr.push(i);
            }
            return num;
        }
        $scope.setCalDis = function () {

            if ($scope.autoCalSets.hxNum > $scope.autoCalSets.zxNum) {
                $scope.projectAutocal.layoutDirection = 'HORIZONTAL';
                $scope.projectAutocal.layoutDirectionDis = '横向';
                $scope.autoCalSets.long = 164;
                $scope.autoCalSets.width = 99.2;
                $scope.projectAutocal.num = $scope.autoCalSets.hxNum;
                $scope.calculates();
            } else {
                $scope.projectAutocal.layoutDirection = 'VERTICAL';
                $scope.projectAutocal.layoutDirectionDis = '纵向';
                $scope.autoCalSets.long = 99.2;
                $scope.autoCalSets.width = 164;
                $scope.projectAutocal.num = $scope.autoCalSets.zxNum;
                $scope.calculates();
            }
            $scope.calcuNum();
            $scope.pic.rowArr = [];
            $scope.pic.rowNumArr = [];
            for (var i = 0; i < $scope.autoCalSets.row; i++) {
                $scope.pic.rowArr.push(i);
            }
            for (var i = 0; i < $scope.autoCalSets.rowNum; i++) {
                $scope.pic.rowNumArr.push(i);
            }
            if ($scope.autoCalSets.wmLong > 4000 || $scope.autoCalSets.wmWidth > 4000) {
                $scope.autoCalSets.showPic = false;
            }
            if ($scope.autoCalSets.showPic) {
                $timeout(function () {
                    $scope.setPic();
                }, 300);
            }

        }
        $scope.setPic = function () {
            var picBg = document.getElementById('picBg');
            $scope.pic.wid = (picBg.offsetWidth - 20) / $scope.pic.rowNumArr.length;
            if ($scope.projectAutocal.layoutDirectionDis == '横向') {
                $scope.pic.hei = $scope.pic.wid * 2 / 3;
            } else {
                $scope.pic.hei = $scope.pic.wid * 1.5;
            }
        }

        if (typeof ($scope.autoCalSets.isFirstIn) === 'undefined') {
            $scope.autoCalSets.isFirstIn = true;
        } else {
            $scope.autoCalSets.isFirstIn = false;
        }


        if ($scope.autoCalSets.isFirstIn) {
            //第一次进入 自动计算选择横向或纵向
            $scope.autoCalSets.width = 99.2;
            $scope.autoCalSets.long = 164;
            $scope.calculates();
            $scope.autoCalSets.hxNum = $scope.calcuNum();
            $scope.autoCalSets.width = 164;
            $scope.autoCalSets.long = 99.2;
            $scope.calculates();
            $scope.autoCalSets.zxNum = $scope.calcuNum();
            $scope.setCalDis();
        }

        $scope.$on('$stateChangeSuccess', function () {
            //获取指定参数,如果不存在就不处理
            $scope.projectAutocal.choiceItem = $lookup.getChoiceItem();
            if ($scope.projectAutocal.choiceItem) {

                switch ($scope.projectAutocal.choiceItem.type) {

                    case 'AZBX_OPTION1':
                        $scope.projectAutocal.layoutOption1 = $scope.projectAutocal.choiceItem.code;
                        $scope.projectAutocal.layoutOption1Dis = $scope.projectAutocal.choiceItem.meaning;
                        break;
                    case 'AZBX_OPTION2':
                        $scope.projectAutocal.layoutOption2 = $scope.projectAutocal.choiceItem.code;
                        $scope.projectAutocal.layoutOption2Dis = $scope.projectAutocal.choiceItem.meaning;
                        break;
                    case 'LAYOUT_DIRECTION':
                        $scope.projectAutocal.layoutDirection = $scope.projectAutocal.choiceItem.code;
                        $scope.projectAutocal.layoutDirectionDis = $scope.projectAutocal.choiceItem.meaning;
                        break;
                    case 'DIP_ROOF':
                        $scope.projectAutocal.layoutAngle = $scope.projectAutocal.choiceItem.code;
                        $scope.projectAutocal.layoutAngleDis = $scope.projectAutocal.choiceItem.meaning;
                        $scope.autoCalSets.componentAngle = parseInt($scope.projectAutocal.choiceItem.meaning);
                        break;
                    default:
                        return;
                }

                $lookup.clearChoiceItem();
            }
        });

        $scope.autoCal = function () {
            if ($scope.autoCalSets.wmLong > 4000 || $scope.autoCalSets.wmWidth > 4000) {
                $cordovaDialogs.confirm('可用尺寸大于40m时将不会显示排布图', '自动计算', ['继续计算', '取消']).then(function (buttonIndex) {

                    if (buttonIndex == 1) {
                        //继续计算
                        $scope.autoCalSets.showPic = false;
                        doCal();
                    }

                    if (buttonIndex == 2) {
                        //取消
                        return;
                    }

                });
            } else {
                $scope.autoCalSets.showPic = true;
                doCal();
                $scope.setPic();
            }

        }

        function doCal() {
            if ($scope.projectAutocal.layoutDirectionDis == "横向") {
                $scope.autoCalSets.long = 164;
                $scope.autoCalSets.width = 99.2;
                $scope.calculates();
                $scope.autoCalSets.hxNum = $scope.calcuNum();
                $scope.projectAutocal.num = $scope.autoCalSets.hxNum;
            } else {
                $scope.autoCalSets.long = 99.2;
                $scope.autoCalSets.width = 164;
                $scope.calculates();
                $scope.autoCalSets.zxNum = $scope.calcuNum();
                $scope.projectAutocal.num = $scope.autoCalSets.zxNum;
            }
            $stateParams.wmInfo.azfx = $scope.projectAutocal.layoutDirection;
            $stateParams.wmInfo.zjsl = $scope.projectAutocal.num;
            $stateParams.wmInfo.azsl = $scope.projectAutocal.num;
            $stateParams.wmInfo.azqj = $scope.projectAutocal.layoutAngle;
            $stateParams.wmInfo.zjjl = $scope.autoCalSets.sumLong;
            $stateParams.wmInfo.ableLong = $scope.autoCalSets.wmLong;
            $stateParams.wmInfo.ableWeith = $scope.autoCalSets.wmWidth;
            $stateParams.wmInfo.neqjl = $scope.autoCalSets.nrqFrontSpacing;
            $stateParams.wmInfo.ewneqjl = $scope.autoCalSets.nrqEastSpacing;
        }

    })


    .controller('ChoosePackCtrl', function ($scope, $task, $stateParams) {

    })

    .controller('TaskDesignMapCtrl', function ($state, $cordovaToast, $cordovaDialogs, $log, $ionicHistory, $timeout, $scope, $task, $stateParams, $dfUtil, $dfHttp, $loading, $user) {
        $scope.projectMap = {};

        $scope.goBack = function () {
            $ionicHistory.goBack();
        }

        $scope.flag = $stateParams.flag;
        angular.copy($stateParams.args, $scope.projectMap);

        $scope.container = 'container' + Math.round(Math.random() * 10000);

        var map;
        var point;
        var pixel;
        var marker;
        var geoc;

        $timeout(function () {
            if (!BMap) {
                $dfUtil.loadJs('baiduScript', 'http://api.map.baidu.com/api?v=2.0&&ak=Lu5gxGyIKnVtLI2b2RjD2s43jktRG8ok&s=1');
                $cordovaDialogs.alert('网络不稳定,地图加载失败,请在网络情况良好的情况下使用!', '验证失败');

                return;
            }
            if (!map) {
                map = new BMap.Map($scope.container, { minZoom: 13, maxZoom: 20 });          // 创建地图实例
                point = new BMap.Point(121.4958580000, 31.2306250000);
                map.centerAndZoom(point, 16);

                marker = new BMap.Marker(map);
                map.addOverlay(marker);
            } else {
                point = new BMap.Point(121.4958580000, 31.2306250000);
                map.centerAndZoom(point, 16);
            }

            map.addControl(new BMap.ScaleControl());
            map.addControl(new BMap.NavigationControl({ type: BMAP_NAVIGATION_CONTROL_SMALL, anchor: BMAP_ANCHOR_TOP_LEFT }));

            changeTagWithPosition(map.getCenter());

            map.enableDragging();
            map.disableInertialDragging();

            geoc = new BMap.Geocoder();

            // 定义一个控件类,即function
            function ZoomControl() {
                // 默认停靠位置和偏移量
                this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
                this.defaultOffset = new BMap.Size(10, 10);
            }

            // 通过JavaScript的prototype属性继承于BMap.Control
            ZoomControl.prototype = new BMap.Control();

            // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
            // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
            ZoomControl.prototype.initialize = function (map) {
                // 创建一个DOM元素
                var div = document.createElement("div");
                // 添加文字说明
                div.innerHTML = ("<img src='img/location_icon.png' style='height: 35px;width: 35px;'/>");
                // 设置样式
                div.style.cursor = "pointer";
                div.style.border = "0px solid gray";
                div.style.backgroundColor = "white";
                div.style.marginBottom = "-5px";

                // 绑定事件,点击一次放大两级
                div.onclick = function (e) {
                    //map.setZoom(map.getZoom() + 2);
                    if (ionic.Platform.isAndroid()) {
                        baidu_location.getCurrentPosition(successCallback, failedCallback);
                    } else {
                        navigator.geolocation.getCurrentPosition(iosSuccessCallback, failedCallback);
                    }
                }
                // 添加DOM元素到地图中
                map.getContainer().appendChild(div);
                // 将DOM元素返回
                return div;
            }
            // 创建控件
            var myZoomCtrl = new ZoomControl();

            map.addControl(myZoomCtrl);

            map.addEventListener('touchmove', function (e) {
                //console.log(e);
                if (((!e.scale && !e.rotation) || (e.scale == 1 && e.rotation == 0)) && e.touches.length == 1 && !zoomFlag) {
                    console.log(e);
                    //console.log(e.target.getCenter());
                    changeTagWithPosition(e.currentTarget.getCenter());
                    pixel.x = pixel.x - 1 * (e.pixel.x - makePixel.x);
                    pixel.y = pixel.y - 1 * (e.pixel.y - makePixel.y);

                    //marker.setPosition(map.pixelToPoint(pixel));
                    changeTagWithPosition(map.pixelToPoint(pixel));
                } else {

                }
            });

            var makePixel;
            var zoomPoint;
            var zoomFlag;


            map.addEventListener('touchstart', function (e) {
                makePixel = e.pixel;
            });

            map.addEventListener('touchend', function (e) {
                zoomFlag = false;
            });

            map.addEventListener('zoomend', function (e) {
                console.log(e);
                $timeout(function () {
                    changeTagWithPosition(point);
                    map.panTo(point);
                }, 50);
                zoomFlag = true;
            });


            //map.addEventListener('dragend',function(e){
            //  console.log(e);
            //});
            //
            //map.addEventListener('click',function(e){
            //  console.log(e);
            //});
        });
        //}

        $scope.submitPosition = function (e) {
            $loading.show("提交中....");
            $user.getCurrentUser().executeSuccess(function (user) {
                if (!$scope.projectMap.longitude || !$scope.projectMap.latitude) {

                }
                $task.submitPosition(user.userId, $scope.projectMap.projectId, $scope.projectMap.longitude, $scope.projectMap.latitude)
                    .success(function (data) {
                        if (data.code == 'SUCCESS') {
                            $stateParams.args.longitude = $scope.projectMap.longitude;
                            $stateParams.args.latitude = $scope.projectMap.latitude;
                            $loading.showSuccess(data.msg);
                            if ($scope.flag == "BasicToMap") {
                                $ionicHistory.goBack();
                            }
                            return;
                        }
                        $loading.showError(data.msg);
                    }).error(function (data) {
                        $loading.showError("网络异常...请稍后再试");
                    })
            });
        }

        $scope.forwardSurvey = function (e) {
            $ionicHistory.goBack();
            $state.go('tab.task-survey', { args: $scope.projectMap });
            e.stopPropagation();
        }

        function changeTagWithPosition(position) {
            point = position;
            pixel = map.pointToPixel(point);
            marker.setPosition(position);
            $timeout(function (e) {
                $scope.projectMap.longitude = position.lng;
                $scope.projectMap.latitude = position.lat;
            }, 10);
        }

        function successCallback(data) {
            var flag = false;

            if (data.latitude >= 0.01 && data.longitude >= 0.01) {
                flag = true;
            }

            if (flag) {
                if (!map) {
                    map = new BMap.Map($scope.container, { minZoom: 13, maxZoom: 20 });          // 创建地图实例
                    var point = new BMap.Point(data.longitude, data.latitude);  // 创建点坐标
                    map.centerAndZoom(point, 16);

                    marker = new BMap.Marker(map);
                    map.addOverlay(marker);
                } else {
                    var point = new BMap.Point(data.longitude, data.latitude);  // 创建点坐标
                    map.centerAndZoom(point, 16);
                }
                changeTagWithPosition(point);
            } else {
                $cordovaToast.showShortBottom('定位失败,请确认GPRS开启情况下使用定位,或者拖动地图到指定地点');
            }
        }

        function iosSuccessCallback(gpsData) {
            //坐标转换完之后的回调函数
            var translateCallback = function (data) {
                if (data.status === 0) {
                    map.centerAndZoom(data.points[0], 16);
                    changeTagWithPosition(data.points[0]);
                }
            }

            var gpsPosition = new BMap.Point(gpsData.coords.longitude, gpsData.coords.latitude);


            var convertor = new BMap.Convertor();
            var pointArr = [];
            pointArr.push(gpsPosition);
            convertor.translate(pointArr, 1, 5, translateCallback)

            //$dfUtil.convertGpsToBaiduGps([data.coords.longitude + ',' + data.coords.latitude]).success(function (array) {
            //    $log.log(array);
            //    for (key in array) {
            //        $log.log(key + ":::" + data['' + key + '']);
            //        for (mm in data['' + key + '']) {
            //            $log.log(mm + ":::" + data['' + key + '']['' + mm + '']);
            //        }
            //    }
            //    if (array.length > 0) {
            //        var xy = array[0];
            //        var point = new BMap.Point(xy.x, xy.y);  // 创建点坐标
            //        map.centerAndZoom(point, 16);
            //        changeTagWithPosition(point);
            //    }
            //});

        }

        function failedCallback(data) {
            for (key in data) {
                console.log(key + ":::" + data['' + key + '']);
                for (mm in data['' + key + '']) {
                    console.log(mm + ":::" + data['' + key + '']['' + mm + '']);
                }
            }

        }

        $timeout(function () {
            if (ionic.Platform.isAndroid()) {

                baidu_location.getCurrentPosition(successCallback, failedCallback);
            } else {
                navigator.geolocation.getCurrentPosition(iosSuccessCallback, failedCallback);
            }
        }, 700);
    })

    .controller('TaskDesignCtrl', function ($ionicPopup, $ionicActionSheet, $cordovaDialogs, $ionicHistory, $dfUtil, $timeout, $scope, $task, $lookup, $state, $stateParams, $ionicSlideBoxDelegate, $ionicScrollDelegate, $design, $dfBoradcast, $user, $dfCache, $dfHttp, $http, $loading, $imageUploadCache, $interval, $cordovaFile) {

        window.currentProjectId = $stateParams.args.projectId;
        $scope.goInputText = function (obj, propName) {
            $state.go('tab.task-common-textarea', {
                args: {
                    obj: obj,
                    propName: propName
                }
            });
        }

        $scope.shareTapped = function () {
            //分享
            var cancelActionSheet = $ionicActionSheet.show({
                buttons: [{ text: '分享到QQ' }, { text: '分享到微信' }],
                cancelText: '取消',
                cancel: function () {
                    return true;
                },
                buttonClicked: function (index) {
                    cancelActionSheet();
                    switch (index) {
                        case 0:
                            //分享到qq
                            shareToQQ();
                            break;
                        case 1:
                            //分享到微信
                            shareToWeChat();
                            break;
                    }
                }
            })
        }

        //TODO: appId、appName
        //cordova-plugin-qq 配置
      if(typeof QQ !== "undefined") {
        QQ.setOptions({
          appId: '1104756067',
          appName: '航天分布式',
          appKey: 'zG08oJyBQpugsKt5'
        });
      }

        /**
         * qq分享
         */
        function shareToQQ() {
            if (typeof QQ === 'undefined') {
                alert('QQ plugin not ready');
                return;
            } else {


              //分享到联系人
              QQ.share('这是QQ分享的内容',
                '标题',
                'http://guanshuyang.com/demo/img/userHad.png',
                'http://123.207.121.204/app-zy/solution.html?projectId=' + window.currentProjectId,
                function (ok) {
                  alert('share: ' + (ok ? 'okay' : 'cancelled'));
                }, function (err) {
                  alert('share fail, err:' + err);
                });
            }


        }

        /**
         * 微信分享
         */
        function shareToWeChat() {
            if (typeof Wechat === "undefined") {
                alert("未安装cordova微信插件");
                return;
            } else {
                //检测是否安装微信
                Wechat.isInstalled(function (installed) {

                    if (installed) {
                        var shareWParams = {
                            message: {
                                media: {}
                            },
                            scene: Wechat.Scene.SESSION
                        };
                        shareWParams.message.title = "testTitle";
                        shareWParams.message.description = "testDescription";
                        shareWParams.message.thumb = "img/adam.jpg";
                        shareWParams.message.media.type = Wechat.Type.WEBPAGE;
                        shareWParams.message.media.webpageUrl = 'http://pm.ht-home.cn/app-zy/solution.html?projectId=' + window.currentProjectId;
                        //分享到微信会话
                        Wechat.share(shareWParams, function () {
                            //分享成功
                        }, function (reason) {
                            alert("分享失败: " + reason);
                        });
                    } else {
                        alert("您尚未安装微信。");
                    }
                }, function (reason) {
                    alert("Failed: " + reason);
                });

            }
        }

        $scope.onTouchThis = function ($event) {
            // console.log($event);
            $ionicSlideBoxDelegate.enableSlide(false);
            $ionicSlideBoxDelegate.$getByHandle('slide-box').enableSlide(false);
        };

        $scope.onDragThis = function ($event) {
            //console.log($event);
            $ionicSlideBoxDelegate.$getByHandle('slide-box').enableSlide(true);
        };

        $scope.goChoicePhoto = function (properties, code) {
            $state.go('tab.task-common-choicePhoto', {
                args: {
                    properties: properties,
                    code: code
                }
            })
        }

        $scope.backToTask = function () {

            var oldData = $dfCache.getObject('designInfo$' + $scope.projectSolution.projectId);
            var isNewInfo = false;

            for (var key in oldData) {

                if (key == "spmsSurveyWmList" && oldData.spmsSurveyWmList) {
                    for (var i = 0; i < oldData.spmsSurveyWmList.length; i++) {

                        for (var roomKey in oldData.spmsSurveyWmList[i]) {
                            if (oldData.spmsSurveyWmList[i]['' + roomKey + ''] != $scope.projectSolution.spmsSurveyWmList[i]['' + roomKey + '']) {
                                isNewInfo = true;
                                break;
                            }
                        }

                    }
                }
                if (key == "classList" && oldData.classList) {
                    for (var i = 0; i < oldData.classList.length; i++) {
                        if (angular.toJson(oldData.classList[i]) != angular.toJson($scope.projectSolution.classList[i])) {
                            isNewInfo = true;
                            break;
                        }
                    }
                }

                if (oldData["" + key + ""] != $scope.projectSolution["" + key + ""]) {

                    if (key.length > 3 && key.substring(key.length - 3, key.length) == "Dis") {
                        continue;
                    }

                    if (key == "spmsSurveyWmList" || key == "classList" || key == "choiceItem" || key == "finalXd" || key == "showNbq1" || key == "showNbq2" || key == "zcs" || key == "jiajuAndGuagouQty" || key == "showPdx" || key == "sumGl") {
                        continue;
                    }
                    isNewInfo = true;
                    break;
                }
            }

            if (oldData.projectId && !isNewInfo) {
                $state.go('tab.tasks', {}, { reload: true });
                $ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
            } else if (oldData.projectId) {
                $cordovaDialogs.confirm('方案数据未保存,确定要返回吗?', '方案数据', ['保存并返回', '直接返回']).then(function (buttonIndex) {
                    if (buttonIndex == 2) {
                        $state.go('tab.tasks', {}, { reload: true });
                        $ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
                    }

                    if (buttonIndex == 1) {
                        $dfCache.putObject('designInfo$' + $scope.projectSolution.projectId, $scope.projectSolution);

                        $state.go('tab.tasks', {}, { reload: true });
                        $ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
                    }
                });
            } else {
                $state.go('tab.tasks', {}, { reload: true });
                $ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
            }
        }

        $dfUtil.changecss('.scroll-height', 'height', document.body.scrollHeight - 128 + 'px');

        $scope.lazyLoad = false;

        $timeout(function () {
            $scope.lazyLoad = true;
        }, 1000);

        $scope.slideHeight = {
            'height': document.body.scrollHeight - 128 + 'px'
        }

        $scope.slideHeightPx = document.body.scrollHeight - 128;

        $scope.navi = {
            'currentIndex': 0
        }

        //TODO:直接取HT60-156P-4BB-265光伏组件的额定功率
        var component = $design.getWithProperty({
            '$and': [{ 'categoryCode': 'A0301' },
            { 'itemCode': 'HT60-156P-4BB-265' }]
        });
        var powerRating = component[0].edgl;


        //自动计算
        $scope.forwardAutocal = function (wmInfo) {
            $state.go('tab.task-design-autocal', { args: $stateParams.args, wmInfo: wmInfo });
        }

        $scope.delegate = $ionicSlideBoxDelegate;
        $timeout(function () {
            $scope.delegate.update();
            $scope.delegate.enableSlide(false);
        }, 200);

        $scope.curStyle = 0;
        $scope.curSubStyle = 0;

        $scope.activeNav = function ($event) {
            $scope.saveDesign(false);
            $scope.delegate.update();
            $scope.delegate.enableSlide(false);
            var currentElem = $event.target;
            var parentElem = document.getElementById("design-nav-scroll");
            var index = 0;
            for (var i = 0; i < parentElem.children.length; i++) {
                if (currentElem == parentElem.children[i]) {
                    $scope.curStyle = i;
                    $scope.navi.currentIndex = i;
                    currentElem.className = 'active';
                    $scope.vm['lazyLoad' + (i + 1)] = true;
                    //console.log(i);
                } else {
                    parentElem.children[i].className = "";
                    $scope.vm['lazyLoad' + (i + 1)] = false;
                }
                //var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-box');
                //if ($scope.curStyle < sildeBox.slidesCount()) {
                //  sildeBox.slide($scope.curStyle, 500);
                //  sildeBox.update();
                //}
            }

            if ($scope.curStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTo(($scope.curStyle - 2) * 80, 0, true);
            }
            if ($scope.curStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTop(true);
            }
        }

        $scope.activeSlide = function (index) {
            $scope.navi.currentIndex = index;
            var parentElem = document.getElementById("design-nav-scroll");
            for (var i = 0; i < parentElem.children.length; i++) {
                if (index == i) {
                    $scope.curStyle = i;
                    var currentElem = parentElem.children[i];
                    currentElem.className = 'active';
                    //console.log(i);
                } else {
                    parentElem.children[i].className = "";
                }
            }

            var sildeBox = $ionicSlideBoxDelegate.$getByHandle('slide-box');
            sildeBox.slide($scope.curStyle, 500);
            sildeBox.update();
            if ($scope.curStyle > 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTo(($scope.curStyle - 2) * 80, 0, true);
            }
            if ($scope.curStyle <= 2) {
                $ionicScrollDelegate.$getByHandle('nav-scroll').scrollTop(true);
            }
        }

        $scope.projectSolution = {
            "spmsSurveyWmList": [
                {
                    "ableLong": '',
                    "ableWeith": '',
                    "arrPhoto": '',
                    "azfx": '',
                    "azqj": '',
                    "azsl": '',
                    "bwwdlx": '',
                    "neqjl": '',
                    "ewneqjl": '',
                    "nrqHeigth": '',
                    "projectId": '',
                    "surveyWmId": '',
                    "wdcx": '',
                    "wmLong": '',
                    "wmWeith": '',
                    "wmqj": '',
                    "wmtq": '',
                    "wmxz": '',
                    "zjjl": '',
                    "zjsl": '',
                    'arr_photo': ''
                }],
            'userId': '',
            'solutionId': '',
            'projectId': '',
            'calculatedModulesNum': '',
            'layoutOption1': '',
            'layoutOption2': '',
            'layoutOption3': '',
            'layoutOption4': '',
            'layoutOption1Dis': '',
            'layoutOption2Dis': '',
            'layoutOption3Dis': '',
            'layoutOption4Dis': '',
            'layoutInverter': '',
            'layoutFljd': '',
            'productModel': '',
            'modulesNum': '',
            'dg1a': '',
            'dg2a': '',
            'dg3a': '',
            'dg1b': '',
            'dg2b': '',
            'zj1a': '',
            'zj2a': '',
            'zj3a': '',
            'zj1b': '',
            'zj2b': '',
            'zcNum': '',
            'zcNumDis': '',
            'zcs': '',
            'zc1CptsNum': '',
            'zc2CptsNum': '',
            'zc3CptsNum': '',
            'zc4CptsNum': '',
            'inverter1': '',
            'inverter1Dis': '',
            'inverter2': '',
            'inverter2Dis': '',
            'jiaju': '',
            'jiajuDis': '',
            'jiajuLsType': '',
            'jiajuLsTypeDis': '',
            'guagou': '',
            'guagouDis': '',
            'guagouLsType': '',
            'guagouLsTypeDis': '',
            'jiajuQty': '',
            'guagouQty': '',
            'jiajuAndGuagouQty': '',
            'zyk': '',
            'byk': '',
            'ddp': '',
            'jdj': '',
            'pdx': '',
            'pdxDis': '',
            'pdxdby': '',
            'pdxdbyDis': '',
            'zldl': '',
            'jldl': '',
            'hgjt': '',
            'others': '',
            'nbqazwz': '',
            'packDis': '',
            'xdType': '',
            'xdType2': '',
            'xdTypeDis': '',
            'xdType2Dis': '',
            'finalXd': '',
            'showNbq1': false,
            'showNbq2': false,
            'showPdx': false,
            'dbw': '',
            'remark': '',
            'uploaded': '',
            'sumGl': '',
            'zjl': '',
            'fljd': '支架安装好后,导轨需接地.屋面有防雷带,支架接地至防雷带,若无防雷带,使用到导线引到地面接地.制作接地体,将电表箱,逆变器,支架引下线(如有)接地.接地体以黄黑漆涂抹标记.'
        };

        //上传草图
        $scope.choiceImage = function (imageClass) {
            $state.go('tab.task-common-photo', {
                args: {
                    funId: $scope.projectSolution.projectId,
                    funName: 'PROJECT',
                    imageClass: imageClass
                }
            });
        }
        for (var key in $stateParams.args) {
            if (key == 'remark') {
                continue;
            }
            $scope.projectSolution['' + key + ''] = $stateParams.args['' + key + ''];
        }

        $user.getCurrentUser().executeSuccess(function (user) {

            $scope.user = user;
            $scope.projectSolution.userId = user.userId;

            $scope.getCache();
            $dfCache.putObject('designInfo$' + $scope.projectSolution.projectId, angular.copy($scope.projectSolution));
            if ($scope.projectSolution.uploaded || $scope.projectSolution.uploaded === '') {
                $task.getDesignInfo($scope.projectSolution.userId, $scope.projectSolution.projectId).success(function (data) {
                    if (data.code == 'SUCCESS') {
                        $scope.projectSolution.uploaded = false;
                        if (data.data) {
                            $scope.setData(data.data);
                            $scope.projectSolution.userId = $scope.user.userId;
                            if (data.data.solutionId) {
                                $dfCache.putObject('designInfo$' + $scope.projectSolution.projectId, angular.copy($scope.projectSolution));
                            }
                        }
                    }
                }).error(function (data) {
                });
            } else {

            }

        });

        $scope.cal = { x: 0, y: 0, z: 0, a: 0, b: 0 };
        $scope.setNum = function (obj) {
            if (parseInt(obj.zj1a) + '' == obj.zj1a) {
                $scope.cal.x = obj.zj1a;
            }
            if (parseInt(obj.zj2a) + '' == obj.zj2a) {
                $scope.cal.y = obj.zj2a;
            }
            if (parseInt(obj.zj3a) + '' == obj.zj3a) {
                $scope.cal.z = obj.zj3a;
            }
            if (parseInt(obj.zj1b) + '' == obj.zj1b) {
                $scope.cal.a = obj.zj1b;
            }
            if (parseInt(obj.zj2b) + '' == obj.zj2b) {
                $scope.cal.b = obj.zj2b;
            }
        }

        $scope.calcuZc = function () {
            $scope.projectSolution.zcNum = 0;
            if (1 * $scope.projectSolution.zc1CptsNum > 0) {
                $scope.projectSolution.zcNum++;
            }
            if (1 * $scope.projectSolution.zc2CptsNum > 0) {
                $scope.projectSolution.zcNum++;
            }
            if (1 * $scope.projectSolution.zc3CptsNum > 0) {
                $scope.projectSolution.zcNum++;
            }
            if (1 * $scope.projectSolution.zc4CptsNum > 0) {
                $scope.projectSolution.zcNum++;
            }
            if ($scope.projectSolution.modulesNum.length == 0) {
                $scope.projectSolution.modulesNum = 0;
            }
            $scope.projectSolution.zcs = 1 * $scope.projectSolution.zc1CptsNum + 1 * $scope.projectSolution.zc2CptsNum + 1 * $scope.projectSolution.zc3CptsNum + 1 * $scope.projectSolution.zc4CptsNum;
            $scope.projectSolution.zcNumDis = $scope.projectSolution.zcNum + '组 ' + $scope.projectSolution.zcs + '/' + $scope.projectSolution.modulesNum + '块';
        }

        $scope.calcuJiajuAndGuagouQty = function () {
            $scope.projectSolution.jiajuAndGuagouQty = 4 * $scope.cal.x + 6 * $scope.cal.y + 8 * $scope.cal.z + 4 * $scope.cal.a + 8 * $scope.cal.b;
        }
        $scope.calcuJiajuAndGuagou = function (type) {
            if (type == 'calcuJia') {
                calcuJia = false;
                if ($scope.projectSolution.guagouQty > $scope.projectSolution.jiajuAndGuagouQty) {
                    $scope.projectSolution.guagouQty = $scope.projectSolution.jiajuAndGuagouQty;
                    $scope.projectSolution.jiajuQty = 0;
                    return;
                }
                $scope.projectSolution.jiajuQty = $scope.projectSolution.jiajuAndGuagouQty - $scope.projectSolution.guagouQty;
            } else if (type == 'calcuGua') {
                calcuGua = false;
                if ($scope.projectSolution.jiajuQty > $scope.projectSolution.jiajuAndGuagouQty) {
                    $scope.projectSolution.jiajuQty = $scope.projectSolution.jiajuAndGuagouQty;
                    $scope.projectSolution.guagouQty = 0;
                    return;
                }
                $scope.projectSolution.guagouQty = $scope.projectSolution.jiajuAndGuagouQty - $scope.projectSolution.jiajuQty;
                calcuJia = false;
            }
        };
        $scope.calcuZyk = function () {
            $scope.projectSolution.zyk = 1 * $scope.cal.x + 2 * $scope.cal.y + 4 * $scope.cal.z + 2 * $scope.cal.b;
        };
        $scope.calcuByk = function () {
            $scope.projectSolution.byk = 4 * $scope.cal.x + 4 * $scope.cal.y + 4 * $scope.cal.z + 4 * $scope.cal.a + 4 * $scope.cal.b;
        };
        $scope.calcuDdp = function () {
            $scope.projectSolution.ddp = 2 * $scope.cal.x + 2 * $scope.cal.y + 4 * $scope.cal.z + 2 * $scope.cal.a + 2 * $scope.cal.b;
        };
        $scope.calcuJdj = function () {
            $scope.projectSolution.jdj = 2 * $scope.cal.x + 2 * $scope.cal.y + 2 * $scope.cal.z + 2 * $scope.cal.a + 2 * $scope.cal.b;
        };

        $scope.calcus = function () {
            $scope.setNum($scope.projectSolution);
            var cal = $scope.cal;
            if (cal.x == 0 && cal.y == 0 && cal.z == 0 && cal.a == 0 && cal.b == 0) {
                return;
            }
            $scope.calcuJiajuAndGuagouQty();
            $scope.calcuZyk();
            $scope.calcuByk();
            $scope.calcuDdp();
            $scope.calcuJdj();
        };

        $scope.getCache = function () {
            var data = $dfCache.getObject('designInfo$' + $scope.projectSolution.projectId);
            if (data) {
                $scope.projectSolution.spmsSurveyWmList = data.spmsSurveyWmList;
                if (!data.uploaded && data.uploaded !== "") {
                    $scope.setData(data);
                }
                $scope.projectSolution.userId = $scope.user.userId;
            }
        }

        $scope.getDescByProperties = function (properties) {
            var result = $design.getWithProperty(properties);
            if (result.length > 0) {
                return result[0].itemDesc;
            } else {
                return '';
            }
        };

        $scope.setData = function (data) {

            for (var key in data) {
                $scope.projectSolution['' + key + ''] = data['' + key + ''];
                switch (key) {
                    case 'productModel':
                        if (data.productModel == "HT-OTHER") {
                            $scope.projectSolution.packDis = '其他 ' + $scope.projectSolution.modulesNum + '块';
                        } else {
                            $scope.projectSolution.packDis = $scope.getDescByProperties({ 'itemCode': data.productModel }) + ' ' + $scope.projectSolution.modulesNum + '块';
                        }
                        break;
                    case 'inverter1':
                        $scope.projectSolution.inverter1Dis = $scope.getDescByProperties({ 'itemCode': data.inverter1 });
                        break;
                    case 'inverter2':
                        $scope.projectSolution.inverter2Dis = $scope.getDescByProperties({ 'itemCode': data.inverter2 });
                        break;
                    case 'jiaju':
                        $scope.projectSolution.jiajuDis = $scope.getDescByProperties({ 'itemCode': data.jiaju });
                        break;
                    case 'guagou':
                        $scope.projectSolution.guagouDis = $scope.getDescByProperties({ 'itemCode': data.guagou });
                        break;
                    case 'jiajuLsType':
                        $scope.projectSolution.jiajuLsTypeDis = $scope.getDescByProperties({ 'itemCode': data.jiajuLsType });
                        break;
                    case 'guagouLsType':
                        $scope.projectSolution.guagouLsTypeDis = $scope.getDescByProperties({ 'itemCode': data.guagouLsType });
                        break;
                    case 'pdx':
                        $scope.projectSolution.pdxDis = $scope.getDescByProperties({ 'itemCode': data.pdx });
                        break;
                    default:
                        break;
                }
            }

            for (var key2 in data.spmsSurveyWmList) {
                $scope.projectSolution.spmsSurveyWmList['' + key2 + ''] = data.spmsSurveyWmList['' + key2 + ''];
            }

            if (!(typeof ($scope.projectSolution.spmsSurveyWmList) == "undefined")) {
                for (var i = 0; i < $scope.projectSolution.spmsSurveyWmList.length; i++) {
                    $scope.$watch('projectSolution.spmsSurveyWmList[' + i + '].azsl', function () {
                        $scope.projectSolution.calculatedModulesNum = 0;
                        for (var i = 0; i < $scope.projectSolution.spmsSurveyWmList.length; i++) {
                            if (!isNaN(parseInt($scope.projectSolution.spmsSurveyWmList[i].azsl))) {
                                $scope.projectSolution.calculatedModulesNum += $scope.projectSolution.spmsSurveyWmList[i].azsl;
                            }
                        }
                        $scope.projectSolution.sumGl = $scope.projectSolution.calculatedModulesNum * powerRating / 1000;

                        if (isNaN($scope.projectSolution.calculatedModulesNum)) {
                            $scope.projectSolution.calculatedModulesNum = 0;
                            $scope.projectSolution.sumGl = 0;
                        }

                        $scope.projectSolution.zjl = $scope.projectSolution.sumGl;

                    });
                }
            }

            $scope.projectSolution.layoutOption1 = data.spmsSurveyZxfs;

            for (var key1 in $scope.projectSolution) {
                if (angular.isString($scope.projectSolution['' + key1 + ''])) {
                    $lookup.getWithLookupCode($scope.projectSolution['' + key1 + ''], key1).executeSuccess(function (lookup) {
                        if (lookup.lookupCode) {
                            $scope.projectSolution['' + lookup.options + 'Dis'] = lookup.lookupMeaning;
                        }
                    })
                }
                if (key1 == 'xdType') {
                    if ($scope.projectSolution['' + key1 + ''] == "SINGEL_PHASE") {
                        $scope.projectSolution.xdTypeDis = '单相';
                    } else if ($scope.projectSolution['' + key1 + ''] == "THREE_PHASE") {
                        $scope.projectSolution.xdTypeDis = '三相';
                    }
                }
                if (key1 == 'xdType2') {
                    if ($scope.projectSolution['' + key1 + ''] == "SINGEL_PHASE") {
                        $scope.projectSolution.xdType2Dis = '单相';
                    } else if ($scope.projectSolution['' + key1 + ''] == "THREE_PHASE") {
                        $scope.projectSolution.xdType2Dis = '三相';
                    }
                }
                if (key1 == 'pdxdby') {
                    if ($scope.projectSolution['' + key1 + ''] == "SOMETHING") {
                        $scope.projectSolution.pdxdbyDis = '有';
                    } else if ($scope.projectSolution['' + key1 + ''] == "NOTHING") {
                        $scope.projectSolution.pdxdbyDis = '无';
                    }
                }
            }
        }

        $scope.$watch('projectSolution.zj1a', function () {
            if (!isNaN(parseInt($scope.projectSolution.zj1a))) {
                $scope.projectSolution.dg1a = parseInt($scope.projectSolution.zj1a) * 2;
            }
            $scope.calcus();
        });
        $scope.$watch('projectSolution.zj2a', function () {
            if (!isNaN(parseInt($scope.projectSolution.zj2a))) {
                $scope.projectSolution.dg2a = parseInt($scope.projectSolution.zj2a) * 2;
            }
            $scope.calcus();
        });
        $scope.$watch('projectSolution.zj3a', function () {
            if (!isNaN(parseInt($scope.projectSolution.zj3a))) {
                $scope.projectSolution.dg3a = parseInt($scope.projectSolution.zj3a) * 2;
            }
            $scope.calcus();
        });
        $scope.$watch('projectSolution.zj1b', function () {
            if (!isNaN(parseInt($scope.projectSolution.zj1b))) {
                $scope.projectSolution.dg1b = parseInt($scope.projectSolution.zj1b) * 2;
            }
            $scope.calcus();
        });
        $scope.$watch('projectSolution.zj2b', function () {
            if (!isNaN(parseInt($scope.projectSolution.zj2b))) {
                $scope.projectSolution.dg2b = parseInt($scope.projectSolution.zj2b) * 2;
            }
            $scope.calcus();
        });

        $scope.$watch('projectSolution.zc1CptsNum', function () {
            if (isNaN(parseInt($scope.projectSolution.zc1CptsNum))) {
                $scope.projectSolution.zc1CptsNum = 0;
            }
            $scope.calcuZc();
        });
        $scope.$watch('projectSolution.zc2CptsNum', function () {
            if (isNaN(parseInt($scope.projectSolution.zc2CptsNum))) {
                $scope.projectSolution.zc2CptsNum = 0;
            }
            $scope.calcuZc();
        });
        $scope.$watch('projectSolution.zc3CptsNum', function () {
            if (isNaN(parseInt($scope.projectSolution.zc3CptsNum))) {
                $scope.projectSolution.zc3CptsNum = 0;
            }
            $scope.calcuZc();
        });
        $scope.$watch('projectSolution.zc4CptsNum', function () {
            if (isNaN(parseInt($scope.projectSolution.zc4CptsNum))) {
                $scope.projectSolution.zc4CptsNum = 0;
            }
            $scope.calcuZc();
        });
        var calcuJia = false;
        var calcuGua = false;
        $scope.$watch('projectSolution.jiajuQty', function () {
            if (!isNaN(parseInt($scope.projectSolution.jiajuQty))) {
                if (!calcuJia) {
                    calcuGua = true;
                    $scope.calcuJiajuAndGuagou('calcuGua');
                }
            }
        });
        $scope.$watch('projectSolution.guagouQty', function () {
            if (!isNaN(parseInt($scope.projectSolution.guagouQty))) {
                if (!calcuGua) {
                    calcuJia = true;
                    $scope.calcuJiajuAndGuagou('calcuJia');
                }
            }
        });

        var isFirstIn = true;
        $timeout(function () {
            $scope.$watch('projectSolution.packDis', function () {
                //选择产品包后
                $scope.projectSolution.showNbq1 = false;
                $scope.projectSolution.showNbq2 = false;

                $scope.projectSolution.zcs = 1 * $scope.projectSolution.zc1CptsNum + 1 * $scope.projectSolution.zc2CptsNum + 1 * $scope.projectSolution.zc3CptsNum + 1 * $scope.projectSolution.zc4CptsNum;
                $scope.projectSolution.zcNumDis = $scope.projectSolution.zcNum + '组 ' + $scope.projectSolution.zcs + '/' + $scope.projectSolution.modulesNum + '块';

                var itemCode = $scope.projectSolution.packDis.split(" ")[0];
                var item = $design.getWithProperty({ 'itemDesc': itemCode });
                if (item[0]) {
                    //选择标准包
                    if (parseInt(item[0].ddgl) < 5) {
                        $scope.projectSolution.showNbq1 = true;
                        $scope.projectSolution.xdTypeDis = '单相';
                        $scope.projectSolution.xdType = 'SINGEL_PHASE';
                    } else if (parseInt(item[0].ddgl) > 7) {
                        $scope.projectSolution.showNbq1 = true;
                        $scope.projectSolution.xdTypeDis = '三相';
                        $scope.projectSolution.xdType = 'THREE_PHASE';
                    } else if (parseInt(item[0].ddgl) == 5) {
                        $scope.projectSolution.showNbq1 = true;
                    }
                    if (!isFirstIn) {
                        $scope.projectSolution.pdxdby = undefined;
                        $scope.projectSolution.pdxdbyDis = undefined;
                    } else {
                        isFirstIn = false;
                    }
                    $scope.projectSolution.ddgl = item[0].ddgl;
                    xdChanged();
                } else if ($scope.projectSolution.packDis && $scope.projectSolution.packDis.length == 0) {
                    //未选择
                    resetListData();
                } else {
                    //选择其他
                    $scope.projectSolution.showNbq1 = true;
                    $scope.projectSolution.showNbq2 = true;
                    if (!isFirstIn) {
                        resetListData();
                    }
                }

            });
        }, 500);


        var resetListData = function () {
            $scope.projectSolution.xdType = undefined;
            $scope.projectSolution.xdTypeDis = undefined;
            $scope.projectSolution.xdType2 = undefined;
            $scope.projectSolution.xdType2Dis = undefined;
            $scope.projectSolution.ddgl = undefined;
            $scope.projectSolution.pdxdby = undefined;
            $scope.projectSolution.pdxdbyDis = undefined;
            $scope.projectSolution.inverter1Dis = undefined;
            $scope.projectSolution.inverter1 = undefined;
            $scope.projectSolution.inverter2Dis = undefined;
            $scope.projectSolution.inverter2 = undefined;
            $scope.projectSolution.pdx = undefined;
            $scope.projectSolution.pdxDis = undefined;
        }

        //$scope.$watch('projectSolution.xdType', xdChanged);

        var xdChanged = function () {

            var nbqs;
            if ($scope.projectSolution.ddgl) {
                nbqs = $design.getWithProperty({
                    '$and': [{ 'categoryCode': 'A0302' },
                    { 'ddgl': $scope.projectSolution.ddgl },
                    { 'xd': $scope.projectSolution.xdTypeDis }]
                });
            } else {
                nbqs = $design.getWithProperty({
                    '$and': [{ 'categoryCode': 'A0302' },
                    { 'xd': $scope.projectSolution.xdTypeDis }]
                });
            }

            if (nbqs.length > 1) {
                $scope.projectSolution.showNbq1 = true;
                $scope.projectSolution.showNbq2 = true;
            } else if (nbqs.length > 0) {
                $scope.projectSolution.inverter1Dis = nbqs[0].itemDesc;
                $scope.projectSolution.inverter1 = nbqs[0].itemCode;
                $scope.projectSolution.showNbq1 = true;
                $scope.projectSolution.showNbq2 = false;
            } else {
                $scope.projectSolution.inverter1Dis = undefined;
                $scope.projectSolution.inverter1 = undefined;
                $scope.projectSolution.inverter2Dis = undefined;
                $scope.projectSolution.inverter2 = undefined;
                $scope.projectSolution.showNbq1 = false;
                $scope.projectSolution.showNbq2 = false;
            }
        }

        $scope.$watch('projectSolution.xdTypeDis', function () {
            xdChanged();
            if (($scope.projectSolution.xdTypeDis == '单相' && typeof ($scope.projectSolution.xdType2Dis) == 'undefined') || ($scope.projectSolution.xdTypeDis == '单相' && $scope.projectSolution.xdType2Dis == '单相')) {
                $scope.projectSolution.finalXd = '单相';
            } else {
                $scope.projectSolution.finalXd = '三相';
            }
        });
        $scope.$watch('projectSolution.xdType2Dis', function () {
            if ($scope.projectSolution.xdType2Dis && $scope.projectSolution.xdType2Dis.length > 0) {
                if ($scope.projectSolution.xdTypeDis == '单相' && $scope.projectSolution.xdType2Dis == '单相') {
                    $scope.projectSolution.finalXd = '单相';
                } else {
                    $scope.projectSolution.finalXd = '三相';
                }
            }
        });

        $scope.$watch('projectSolution.pdxdby', function (value) {
            if (value) {
                $scope.projectSolution.showPdx = true;
            } else {
                $scope.projectSolution.showPdx = false;
            }
            if (!isFirstIn) {
                $scope.projectSolution.pdx = undefined;
                $scope.projectSolution.pdxDis = undefined;
            }

        });

        $scope.$watch('projectSolution.finalXd', function (value) {

            if (!isFirstIn) {
                $scope.projectSolution.pdxdbyDis = undefined;
                $scope.projectSolution.pdxdby = undefined;
                $scope.projectSolution.pdxDis = undefined;
                $scope.projectSolution.pdx = undefined;
            }

        });

        $scope.arrayBufferToBase64 = function (buffer) {
            var binary = '';
            var bytes = new Uint8Array(buffer);
            var len = bytes.byteLength;
            for (var i = 0; i < len; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            return window.btoa(binary);
        }

        var countOfzj = '';


        $scope.saveDesign = function (showMsg) {
            //window.open('http://pm.ht-home.cn/v1/controller/showDesignPreview?projectId=1000','_blank',true);
            //return ;

            countOfzj = parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj1a)) * 1 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj2a)) * 2 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj3a)) * 3 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj1b)) * 1 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj2b)) * 2;


            if ($scope.navi.currentIndex == 2 && countOfzj != $scope.projectSolution.modulesNum) {
                if ($scope.projectSolution.modulesNum == 0) {
                    $cordovaDialogs.alert('您已填写支架或组串组件数量,请选择产品包', '请选择产品包');
                } else {
                    $cordovaDialogs.alert('支架数量和产品包数量不匹配', '数量有误');
                }
                return;
            }

            if ($scope.navi.currentIndex == 2 && $scope.projectSolution.zcs != $scope.projectSolution.modulesNum) {
                if ($scope.projectSolution.modulesNum == 0) {
                    $cordovaDialogs.alert('您已填写支架或组串组件数量,请选择产品包', '请选择产品包');
                } else {
                    $cordovaDialogs.alert('组串数和产品包数量不匹配', '数量有误');
                }
                return;
            }
            //暂存方案
            $scope.projectSolution.uploaded = false;
            $dfCache.putObject('designInfo$' + $scope.projectSolution.projectId, angular.copy($scope.projectSolution));
            if (showMsg) {
                $loading.showSuccess('方案数据已暂存');
            }
        }

        $scope.uploadDesign = function () {

            //window.open('http://pm.ht-home.cn/v1/controller/showDesignPreview?projectId=1000','_blank',true);
            //return ;

            countOfzj = parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj1a)) * 1 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj2a)) * 2 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj3a)) * 3 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj1b)) * 1 + parseInt($dfUtil.replaceOfEmpty($scope.projectSolution.zj2b)) * 2;


            if (countOfzj != $scope.projectSolution.modulesNum) {
                if ($scope.projectSolution.modulesNum == 0) {
                    $cordovaDialogs.alert('您已填写支架或组串组件数量,请选择产品包', '请选择产品包');
                } else {
                    $cordovaDialogs.alert('支架数量和产品包数量不匹配', '数量有误');
                }
                return;
            }

            if ($scope.projectSolution.zcs != $scope.projectSolution.modulesNum) {
                if ($scope.projectSolution.modulesNum == 0) {
                    $cordovaDialogs.alert('您已填写组串组件数量,请选择产品包', '请选择产品包');
                } else {
                    $cordovaDialogs.alert('组串数量和产品包数量不匹配', '数量有误');
                }
                return;
            }

            // 上传方案
            $scope.projectSolution.inverter2 = $scope.projectSolution.inverter2 == '' ? undefined : $scope.projectSolution.inverter2;
            $scope.projectSolution.inverter2Dis = $scope.projectSolution.inverter2Dis == '' ? undefined : $scope.projectSolution.inverter2Dis;
            $scope.projectSolution.userId = $scope.user.userId;
            $dfCache.putObject('designInfo$' + $scope.projectSolution.projectId, angular.copy($scope.projectSolution));
            $loading.show('提交中');
            $dfHttp.post("api/survey/createOrUpdateSolution.json", $scope.projectSolution).success(function (data) {
                if (data.code == 'SUCCESS') {
                    $loading.showSuccess(data.msg);
                    $scope.projectSolution.uploaded = true;
                    $dfCache.putObject('designInfo$' + $scope.projectSolution.projectId, angular.copy($scope.projectSolution));
                    $scope.projectSolution.solutionId = data.data.solutionId;

                    var imageCache = $imageUploadCache.getImagesByParams($scope.projectSolution.projectId, 'PROJECT', 'ROOFPHOTO');
                    var imageCache2 = $imageUploadCache.getImagesByParams($scope.projectSolution.projectId, 'PROJECT', 'NBQAZWZCT_FA');
                    var photoDatasArray = [];
                    var photoDatasArray2 = [];

                    angular.forEach(imageCache.images, function (image) {
                        var pickImage = image.imageUrl;
                        var lastIndexOfSlash = pickImage.lastIndexOf('/');
                        var filePath = pickImage.substr(0, lastIndexOfSlash); //p
                        var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

                        $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
                            var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
                            photoDatasArray.push(base64String);
                        }, function (error) {
                            console.log(error);
                            $loading.showError('本地图片没有找到,请确认存在');
                        });

                    });

                    angular.forEach(imageCache2.images, function (image) {
                        var pickImage = image.imageUrl;
                        var lastIndexOfSlash = pickImage.lastIndexOf('/');
                        var filePath = pickImage.substr(0, lastIndexOfSlash); //p
                        var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

                        $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
                            var base64String = $scope.arrayBufferToBase64(arrayBuffer);
                            photoDatasArray2.push(base64String);
                        }, function (error) {
                            console.log(error);
                            $loading.showError('本地图片没有找到,请确认存在');
                        });

                    });

                    if (!imageCache.images) {
                        imageCache.images = [];
                    }
                    if (!imageCache2.images) {
                        imageCache2.images = [];
                    }

                    $scope.timer = $interval(function (e) {

                        if (photoDatasArray.length == imageCache.images.length && imageCache.images.length > 0) {
                            $loading.show('图片提交中..');
                            $task.uploadImage2('PROJECT', $scope.projectSolution.projectId, imageCache.imageClass, photoDatasArray)
                                .success(function (data) {
                                    if (data.code == 'SUCCESS') {
                                        $loading.showSuccess(data.msg);
                                        // $ionicHistory.goBack();
                                    } else {
                                        $loading.showError(data.msg);
                                    }
                                }).error(function (data) {
                                    $loading.showError('网络异常,请稍后再试');
                                });
                            $interval.cancel($scope.timer);
                        }

                    }, 200, 10);

                    $scope.timer2 = $interval(function (e) {

                        if (photoDatasArray2.length == imageCache2.images.length && imageCache2.images.length > 0) {
                            $loading.show('图片提交中..');
                            $task.uploadImage2('PROJECT', $scope.projectSolution.projectId, imageCache2.imageClass, photoDatasArray2)
                                .success(function (data) {
                                    if (data.code == 'SUCCESS') {
                                        $loading.showSuccess(data.msg);
                                        // $ionicHistory.goBack();
                                    } else {
                                        $loading.showError(data.msg);
                                    }
                                }).error(function (data) {
                                    $loading.showError('网络异常,请稍后再试');
                                });
                            $interval.cancel($scope.timer2);
                        }

                    }, 200, 10);

                    $state.go('tab.tasks', {}, { reload: true });
                    $ionicHistory.goToHistoryRoot($ionicHistory.currentHistoryId());
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (data) {
                $loading.showError(data.msg);
            });

        }


        $scope.goDesignChoice = function (properties, selecteds, showOther, dbTag, rightWord, position, haveCancel) {
            if (properties.$and) {
                var array = [];
                for (var i = 0; i < properties.$and.length; i++) {
                    angular.forEach(properties.$and[i], function (value, key) {
                        if (value == '' || typeof (value) == 'undefined') {
                            return;
                        } else {
                            array.push(properties.$and[i]);
                        }
                    })
                }
                properties.$and = array;
            }

            if (dbTag == 'OTHER' || dbTag == 'HT-OTHER') {
                dbTag = $scope.projectSolution.modulesNum;
            }

            var items = $design.getWithProperty(properties);

            $state.go('tab.task-design-choice', {
                'args': {
                    'items': items,
                    'selecteds': selecteds,
                    'showOther': showOther,
                    'dbTag': dbTag,
                    'rightWord': rightWord,
                    'position': position,
                    'haveCancel': haveCancel
                }
            });
        };

        $scope.goDesignChoiceWithCancel = function (properties, selecteds, showOther, dbTag, rightWord, position) {
            if (properties.$and) {
                var array = [];
                for (var i = 0; i < properties.$and.length; i++) {
                    angular.forEach(properties.$and[i], function (value, key) {
                        if (value == '' || typeof (value) == 'undefined') {
                            return;
                        } else {
                            array.push(properties.$and[i]);
                        }
                    })
                }
                properties.$and = array;
            }

            if (dbTag == 'OTHER' || dbTag == 'HT-OTHER') {
                dbTag = $scope.projectSolution.modulesNum;
            }

            var items = $design.getWithProperty(properties);

            $state.go('tab.task-design-choice', {
                'args': {
                    'items': items,
                    'selecteds': selecteds,
                    'showOther': showOther,
                    'dbTag': dbTag,
                    'rightWord': rightWord,
                    'position': position,
                    'haveCancel': true
                }
            });
        };

        $scope.goChoice = function (type, current) {
            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current
                }
            });
        };

        var currentXdIndex = -1;
        $scope.goXdChoice = function (type, current, currentXd) {
            currentXdIndex = currentXd;
            $scope.goChoice(type, current);
        }
        $scope.goChoiceWithOther = function (type, current, otherTitle, otherHolder) {

            $state.go('tab.task-common-choice', {
                'args': {
                    'lookupType': type,
                    'currentCode': current,
                    'showOther': true,
                    'otherName': otherTitle,
                    'otherValue': otherHolder
                }
            });
        };

        $dfBoradcast.getBoradcast('designSelected', function (data) {
            switch (data.category2) {
                case '产品包':
                    if (data.itemCode == 'OTHER') {
                        $scope.projectSolution.productModel = 'HT-OTHER';
                        $scope.projectSolution.modulesNum = parseInt(data.itemDesc);
                        $scope.projectSolution.packDis = '其他 ' + data.itemDesc;
                    } else {
                        $scope.projectSolution.productModel = data.itemCode;
                        $scope.projectSolution.modulesNum = parseInt(data.zjsl);
                        $scope.projectSolution.packDis = data.itemDesc + ' ' + data.zjsl + '块';
                    }
                    break;
                case '逆变器':
                    if (data.position == 0) {
                        $scope.projectSolution.inverter1 = data.itemCode;
                        $scope.projectSolution.inverter1Dis = data.itemDesc;
                    } else if (data.position == 1) {
                        if (data.itemCode == 'cancel') {
                            $scope.projectSolution.inverter2 = '';
                            $scope.projectSolution.inverter2Dis = '';
                            $scope.projectSolution.xdType2 = '';
                            $scope.projectSolution.xdType2Dis = '';
                        } else {
                            $scope.projectSolution.inverter2 = data.itemCode;
                            $scope.projectSolution.inverter2Dis = data.itemDesc;
                        }

                    }
                    break;
                case '交流配电箱':
                    $scope.projectSolution.pdx = data.itemCode;
                    $scope.projectSolution.pdxDis = data.itemDesc;
                    break;
                case '夹具':
                    $scope.projectSolution.jiaju = data.itemCode;
                    $scope.projectSolution.jiajuDis = data.itemDesc;
                    break;
                case '挂钩':
                    $scope.projectSolution.guagou = data.itemCode;
                    $scope.projectSolution.guagouDis = data.itemDesc;
                    break;
                case '螺丝':
                    if (data.position == 0) {
                        //夹具螺丝
                        $scope.projectSolution.jiajuLsType = data.itemCode;
                        $scope.projectSolution.jiajuLsTypeDis = data.itemDesc;
                    } else if (data.position == 1) {
                        //挂钩螺丝
                        $scope.projectSolution.guagouLsType = data.itemCode;
                        $scope.projectSolution.guagouLsTypeDis = data.itemDesc;
                    }
                    break;
                default:
                    break;
            }
        });

        $scope.$on('$stateChangeSuccess', function () {
            $scope.NBQAZWZCT_FA = $imageUploadCache.getImagesCount($scope.projectSolution.projectId, "PROJECT", "NBQAZWZCT_FA") > 0 ? "HAS_IMAGE" : "";

            //获取指定参数,如果不存在就不处理
            $scope.projectSolution.choiceItem = $lookup.getChoiceItem();
            if ($scope.projectSolution.choiceItem) {

                switch ($scope.projectSolution.choiceItem.type) {

                    case 'AZBX_OPTION1':
                        $scope.projectSolution.layoutOption1 = $scope.projectSolution.choiceItem.code;
                        $scope.projectSolution.layoutOption1Dis = $scope.projectSolution.choiceItem.meaning;
                        break;
                    case 'AZBX_OPTION2':
                        $scope.projectSolution.layoutOption2 = $scope.projectSolution.choiceItem.code;
                        $scope.projectSolution.layoutOption2Dis = $scope.projectSolution.choiceItem.meaning;
                        break;
                    case 'AZBX_OPTION3':
                        $scope.projectSolution.layoutOption3 = $scope.projectSolution.choiceItem.code;
                        $scope.projectSolution.layoutOption3Dis = $scope.projectSolution.choiceItem.meaning;
                        break;
                    case 'AZBX_OPTION4':
                        $scope.projectSolution.layoutOption4 = $scope.projectSolution.choiceItem.code;
                        $scope.projectSolution.layoutOption4Dis = $scope.projectSolution.choiceItem.meaning;
                        break;
                    case 'INDOOR_POWER_SOURCE':
                        if (currentXdIndex == 0) {
                            $scope.projectSolution.xdType = $scope.projectSolution.choiceItem.code;
                            $scope.projectSolution.xdTypeDis = $scope.projectSolution.choiceItem.meaning;

                            if ($scope.projectSolution.xdType2Dis && $scope.projectSolution.xdType2Dis.length > 0) {
                                if ($scope.projectSolution.xdTypeDis == '单相' && $scope.projectSolution.xdType2Dis == '单相') {
                                    $scope.projectSolution.finalXd = '单相';
                                } else {
                                    $scope.projectSolution.finalXd = '三相';
                                }
                            } else {
                                $scope.projectSolution.finalXd = $scope.projectSolution.xdTypeDis;
                            }

                        } else if (currentXdIndex == 1) {
                            $scope.projectSolution.xdType2 = $scope.projectSolution.choiceItem.code;
                            $scope.projectSolution.xdType2Dis = $scope.projectSolution.choiceItem.meaning;

                            if ($scope.projectSolution.xdTypeDis == '单相' && $scope.projectSolution.xdType2Dis == '单相') {
                                $scope.projectSolution.finalXd = '单相';
                            } else {
                                $scope.projectSolution.finalXd = '三相';
                            }

                        }
                        break;
                    case 'HAVE_ORNO':
                        $scope.projectSolution.pdxdby = $scope.projectSolution.choiceItem.code;
                        $scope.projectSolution.pdxdbyDis = $scope.projectSolution.choiceItem.meaning;
                        $scope.projectSolution.dbw = $scope.projectSolution.choiceItem.meaning;
                        $scope.projectSolution.showPdx = true;
                        break;
                    default:
                        return;
                }

                $lookup.clearChoiceItem();
            }
        });

        $scope.lazyLoad = false;

        $scope.vm = {};
        $scope.vm.lazyLoad0 = false;
        $scope.vm.lazyLoad1 = false;
        $scope.vm.lazyLoad2 = false;
        $scope.vm.lazyLoad3 = false;
        $scope.vm.lazyLoad4 = false;
        $scope.vm.lazyLoad5 = false;

        $timeout(function () {
            $scope.vm.lazyLoad0 = true;
        }, 300);
        $timeout(function () {
            $scope.vm.lazyLoad1 = true;
        }, 600);
        $timeout(function () {
            $scope.vm.lazyLoad2 = true;
        }, 900);
        $timeout(function () {
            $scope.vm.lazyLoad3 = true;
        }, 1200);
        $timeout(function () {
            $scope.vm.lazyLoad4 = true;
        }, 1500);
        $timeout(function () {
            $scope.vm.lazyLoad5 = true;
        }, 1800);
    })

    //项目自查Ctrl
    .controller("CheckProjectCtrl", function ($scope, $stateParams, $ionicHistory, $user, $dfHttp, $loading, $timeout, $log) {
        //获取当前项目信息
        $scope.project = $stateParams.args;

        //获取当前用户信息
        $user.getCurrentUser().executeSuccess(function (user) {
            $scope.user = user;
        })

        $scope.checkList = {};

        $scope.$on("$ionicView.enter", function () {
            $timeout(function () {
                getCheckList($scope.user.userId, $scope.project.projectId);
            }, 300);
        });

        /**
         * 获取检查列表
         * @param userId
         * @param projectId
         */
        function getCheckList(userId, projectId) {
            $dfHttp.get("api/others/getCheckList.json", {
                "userId": userId,
                projectId: projectId
            }).success(function (data) {
                console.log(data);
                if (data.code == "SUCCESS") {
                    $scope.checkList = data.data;
                } else {
                    $loading.showError("网络出了一点小问题,请稍后再试");
                }
            }).error(function (e) {
                $loading.showError("网络异常,请稍后再试");
            });

            $loading.hide();
        }

        /**
         * 字段完成设置
         * @param obj
         */
        $scope.setFieldFinished = function (obj) {
            obj.checkResult = obj.checkResult == 'TRUE' ? obj.checkResult = 'FALSE' : 'TRUE';
        }

        $scope.isSelectAll = false;

        $scope.allGo = function (myObject) {
            $scope.isSelectAll = !$scope.isSelectAll;
            angular.forEach($scope.checkList.spmsCheckLists, function (obj, i) {
                obj.checkResult = $scope.isSelectAll ? 'TRUE' : 'FALSE';
            })
        }

        /**
         * 保存
         */
        $scope.save = function () {
            save($scope.checkList.spmsCheckLists, $scope.user.userId)
        }

        function save(checkList, userId) {
            $loading.show("正在保存中...");
            $dfHttp.post("api/others/saveCheckList.json", {
                "spmsCheckLists": checkList,
                "userId": userId
            }).success(function (d) {
                if (d.code == "SUCCESS") {
                    $loading.showSuccess(d.msg);
                    $timeout(function () {
                        $loading.hide();
                        $ionicHistory.goBack();
                    }, 500);
                } else {
                    $loading.showError("保存失败");
                }
            }).error(function (e) {
                $loading.showError("网络异常,请稍后再试");
            });
        }
    })
    //进度报告Ctrl
    .controller("ProgressReportCtrl", function ($ionicHistory, $dfUtil, $interval, IMAGES, $q, $imageUploadCache, $cordovaFile, $task, $cordovaDialogs, $rootScope, $scope, $user, $state, $stateParams, $dfHttp, $loading, $dfCache) {
        var progressReportImageUploadStatus = {
            'GGLJC_JD': false,
            'FSCL_JD': false,
            'DGAZ_JD': false,
            'ZJAZ_JD': false,
            'NBQAZ_JD': false,
            'PDXAZ_JD': false
        };

        // 得到项目参数
        $scope.project = $stateParams.args;
        $scope.user = $user.getCurrentUserSync();
        $scope.progressReportList = {};

        $scope.changeReportStatus = function (progressReport) {
            progressReport.cpltResult = (progressReport.cpltResult == 'Y' ? 'N' : 'Y');
        };
        $scope.saveProgressReport = function () {
            $scope.progressReportList.userId = $scope.user.userId;
            $scope.progressReportList.status = 'SAVED';
            $dfCache.putObject('progressReport$' + $scope.project.projectId, $scope.progressReportList);
            $loading.showSuccess('保存成功');
            $ionicHistory.goBack();
        };

        function uploadImageToServer(funId, funName, imageClass) {
            var deferred = $q.defer();
            var promise = deferred.promise;

            promise.success = function (fn) {
                promise.then(fn);
                return promise
            };

            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            };

            var photoDatasArray = [];
            var imageCache = $imageUploadCache.getImagesByParams(funId, funName, imageClass);

            if (!imageCache.images) {
                imageCache.images = [];
            }
            if (imageCache.images.length == 0) {

                deferred.resolve({ code: 'SUCCESS', msg: '没有图片,无需上传', data: { imageClass: imageClass } });
                return promise;
            }

            var count = 0;

            angular.forEach(imageCache.images, function (image) {
                if (image.resource == 'NETWORK') {
                    return;
                }
                count++;
                var pickImage = image.imageUrl;
                var lastIndexOfSlash = pickImage.lastIndexOf('/');
                var filePath = pickImage.substr(0, lastIndexOfSlash); //p
                var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

                $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
                    var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
                    photoDatasArray.push(base64String);
                }, function (error) {
                    deferred.reject({ code: 'LOAD_FILE_ERROR', msg: '本地图片没有找到,请确认存在' });
                });
            });

            if (count == 0) {
                deferred.resolve({ code: 'SUCCESS', msg: '没有图片,无需上传', data: { imageClass: imageClass } });
                return promise;
            }
            //检测图片是否读取完成
            var fileloadTimer = $interval(function (e) {
                if (photoDatasArray.length == count) {
                    $task.uploadImage('PROJECT', $scope.project.projectId, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray)
                        .success(function (data) {
                            if (data.code == 'SUCCESS') {
                                deferred.resolve({ code: 'SUCCESS', msg: data.msg, data: { imageClass: imageCache.imageClass } });
                            } else {
                                deferred.reject({ code: 'FAIL', msg: data.msg });
                            }
                        }).error(function (data) {
                            deferred.reject({ code: 'NETWORK_ERROR', msg: '网络请求链接错误' });
                        });
                    $interval.cancel(fileloadTimer);
                }
            }, 200, 10);

            return promise;
        }
        var user = $user.getCurrentUserSync();


        function submitProgressReportToServer() {
            $loading.show('正在提交进度报告,图片较多,可能需要一段时间...');

            $scope.progressReportList.userId = $scope.user.userId;

            $dfHttp.post('api/others/saveProgress.json', $scope.progressReportList)
                .success(function (data) {
                    if (data.code == 'SUCCESS') {//数据提交成功
                        //开始上传图片
                        $scope.progressReportList.status = 'UPLOADED';
                        angular.forEach(progressReportImageUploadStatus, function (value, key) {
                            uploadImageToServer($scope.project.projectId, 'PROJECT', key)
                                .success(function (obj) {
                                    console.log(obj);
                                    progressReportImageUploadStatus['' + obj.data.imageClass + ''] = true;
                                }).error(function (obj) {
                                    console.log(obj);
                                    progressReportImageUploadStatus['' + obj.data.imageClass + ''] = true;
                                }).error(function (obj) {
                                    console.log(obj);
                                });
                        });
                        var imageUploadTimer = $interval(function (e) {
                            var flag = true;
                            angular.forEach(progressReportImageUploadStatus, function (value, key) {
                                if (!value) {
                                    flag = value;
                                }
                            });
                            if (flag) {
                                $loading.showSuccess('上传成功');
                                $interval.cancel(imageUploadTimer);
                                $ionicHistory.goBack();
                                $task.getCountOfTasks(user.userId);
                                $rootScope.listStatus = "IS_CHECK";
                            }
                        }, 1000, 600);
                    } else {
                        $loading.showError(data.msg);
                    }
                    //此处提交图片
                }).error(function (data) {
                    //网络异常
                    $loading.showError('网络异常,请稍后再试');
                });
        };

        //保存网络图片
        function saveNetworkImage(imageArray) {
            if (!angular.isArray(imageArray)) {
                return;
            }
            angular.forEach(imageArray, function (netImage) {
                console.log(netImage);
                //获取key
                for (var key in netImage) {
                    var keyImageList = netImage['' + key + ''];
                    if (keyImageList && keyImageList.length == 0) {
                        continue;
                    }
                    var imageCache = $imageUploadCache.getImagesByParams($scope.project.projectId, 'PROJECT', key);

                    imageCache.funId = $scope.project.projectId;
                    imageCache.funName = 'PROJECT';
                    imageCache.imageClass = key;

                    var imageList = [];
                    angular.forEach(keyImageList, function (image) {
                        var cacheImage = {};
                        cacheImage.status = 'NEW';
                        cacheImage.imageUrl = image.middleImageUrl;
                        cacheImage.largeImageUrl = image.largeImageUrl;
                        cacheImage.smallImageUrl = image.smallImageUrl;
                        cacheImage.uuid = image.uuid;
                        cacheImage.resource = 'NETWORK';
                        imageList.push(cacheImage);
                    });

                    imageCache.images = imageList;

                    $imageUploadCache.saveImages(imageCache);
                }
            });
        }

        $scope.submitProgressReport = function () {
            for (var index in $scope.progressReportList.progressList) {
                var progressReport = $scope.progressReportList.progressList[index];
                if (progressReport.cpltResult != 'Y') {
                    $cordovaDialogs.alert('进度报告每一项必须完成 且上传图片,才能完工!', '验证失败');
                    return;
                }
            }
            for (var obj in progressReportImageUploadStatus) {
                var count = $imageUploadCache.getImagesCount($scope.project.projectId, 'PROJECT', obj);
                if (count <= 0) {
                    $cordovaDialogs.alert('进度报告每一项必须完成 且上传图片,才能完工!', '验证失败');
                    return;
                }
            }

            $cordovaDialogs.confirm('进度报告完工后,会进入安装完成审核,是否确认完工?', '进度报告完工', ['取消', '确认完工'])
                .then(function (buttonIndex) {
                    if (buttonIndex == 2) {
                        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                            if ($rootScope.networkState == Connection.CELL_3G || $rootScope.networkState == Connection.CELL_4G) {
                                $cordovaDialogs.confirm('进度报告完工,需要上传大量图片,当前网络不在WIFI条件下,是否确认继续提交?', '进度报告', ['取消', '确认完工'])
                                    .then(function (buttonIndex) {
                                        if (buttonIndex == 2) {
                                            submitProgressReportToServer();
                                            $rootScope.listStatus = "ON_GOING";
                                        }
                                    });
                            } else if ($rootScope.networkState == Connection.WIFI) {
                                submitProgressReportToServer();
                            } else if ($rootScope.networkState == Connection.NONE) {
                                $cordovaDialogs.alert('请检查当前网络状态!', '进度报告', '确认');
                            } else {
                                $cordovaDialogs.confirm('进度报告完工,需要上传大量图片,当前网络不在WIFI条件下,是否确认继续提交?', '进度报告', ['取消', '确认完工'])
                                    .then(function (buttonIndex) {
                                        if (buttonIndex == 2) {
                                            submitProgressReportToServer();
                                            $rootScope.listStatus = "ON_GOING";
                                        }
                                    });
                            }
                        } else {
                            submitProgressReportToServer();
                        }
                    }
                    ;
                });
        }

        var progressReportImages = IMAGES.progressReport;

        //上传草图
        $scope.choiceImage = function (imageClass) {
            $state.go('tab.task-common-photo', {
                args: {
                    funId: $scope.project.projectId,
                    funName: 'PROJECT',
                    imageClass: imageClass
                }
            });
        };

        // 监听上传图片按钮
        $scope.$on("$stateChangeSuccess", function () {
            // 循环遍历imaClass
            angular.forEach(progressReportImages, function (data) {
                switch (data) {
                    case "GGLJC_JD":
                        $scope.GGLJC_JD = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                        break;
                    case "FSCL_JD":
                        $scope.FSCL_JD = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                        break;
                    case "DGAZ_JD":
                        $scope.DGAZ_JD = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                        break;
                    case "ZJAZ_JD":
                        $scope.ZJAZ_JD = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                        break;
                    case "NBQAZ_JD":
                        $scope.NBQAZ_JD = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                        break;
                    case "PDXAZ_JD":
                        $scope.PDXAZ_JD = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", data) > 0 ? "HAS_IMAGE" : "";
                        break;
                    default:
                        break;
                }
            })
        });

        //获取进度报告
        $scope.getProgressReport = function () {
            $scope.progressReportList = $dfCache.getObject('progressReport$' + $scope.project.projectId);
            if (!$scope.progressReportList || !$scope.progressReportList.status || $scope.progressReportList.status == 'uploaded') {
                //从网络请求
                var user = $user.getCurrentUserSync();

                $dfHttp.get('api/others/getProgress.json', { "userId": user.userId, "projectId": $scope.project.projectId })
                    .success(function (data) {
                        console.log(data);
                        if (data.code == 'SUCCESS') {
                            $scope.progressReportList = data.data;
                            $scope.progressReportList.userId = user.userId;
                            $scope.progressReportList.status = 'UPLOADED';
                            //从中抽离图片放入缓存
                            var imageList = $scope.progressReportList.classList;
                            //覆盖掉当前缓存中所有图片
                            saveNetworkImage(imageList);
                        } else {
                            $loading.showError(data.msg);
                        }
                    }).error(function (data) {
                        $loading.showError('网络连接异常,请稍后再试!');
                    });
            }
        }

        $scope.getProgressReport();
    })

    //项目分配Ctrl
    .controller("TaskToBeAssignedCtrl", function ($scope, $dfHttp, $dfBoradcast, $cordovaDialogs, $task, $loading, $state, $stateParams, $user, $lookup, $ionicActionSheet, $supplier, $ionicHistory) {

        var projectIntention = {
            "userId": -1,
            "customerName": "",
            "contacts": "",
            "contactsTel": "",
            "distributorCode": "",
            "salesId": "",
            "techId": "",
            "installerCode": "",
            "installerId": "",
            "status": "",
            "regionCode": "",
            "address": "",
            "supportingPoorFlag": "",
            "town": "",
            "village": "",
            "remark": "",
            "resource": ""
        };
        $scope.projectAssigned = { 'title': '选择服务商' };
        $scope.sets = {};

        $scope.project = $stateParams.args;
        if ($stateParams.args.projectId) {

            angular.copy($stateParams.args, projectIntention);
            if (projectIntention.supportingPoorFlag == 'Y') {
                projectIntention.supportingPoorFlagDesc = '是'
            } else {
                projectIntention.supportingPoorFlag = 'N';
                projectIntention.supportingPoorFlagDesc = '否'
            }
        }

        $scope.projectIntention = projectIntention;
        $scope.projectIntention.projectId = $stateParams.args.projectId;

        if ($scope.projectIntention.distributorCode) {
            $scope.sets.haveDistri = true;
            $scope.projectIntention.title = '选择安装商';
            $scope.projectIntention.code = $scope.projectIntention.distributorCode;
        } else {
            $scope.sets.haveDistri = false;
            $scope.projectIntention.title = '选择服务商';
            $scope.projectIntention.code = $scope.projectIntention.installerCode;
        }
        if ($scope.projectIntention.installerCode) {
            $scope.sets.haveInstal = true;
        } else {
            $scope.sets.haveInstal = false;
        }

        //if ($scope.projectIntention.distributorCode) {
        //    var result = $supplier.getWithProperty({ 'providerCode': $scope.projectIntention.distributorCode });
        //    if (result[0]) {
        //        $scope.projectIntention.title = result[0].providerName;
        //    } else {
        //        $loading.showError('服务商编码' + $scope.projectIntention.distributorCode + '找不到对应服务商');
        //    }
        //}

        var items = [];
        $dfHttp.get('api/others/getAllProviders.json?lastUpdateDate=1970-01-01').success(function (data) {
            console.log(data);
            if($scope.sets.haveDistri) {
              for(var i = 0 ; i < data.data.providers.length ; i++) {
                var provider = data.data.providers[i];
                if (provider.installerFlag == 'Y') {
                  items.push(provider);
                }
              }
            }else {
              for(var i = 0 ; i < data.data.providers.length ; i++) {
                var provider = data.data.providers[i];
                if (provider.distributorFlag == 'Y') {
                  items.push(provider);
                }
              }
            }
            //items = data.data.providers;
        });

        $scope.goAssignedChoice = function (properties, selecteds, dbTag, $dfHttp) {

            if ($scope.sets.haveDistri) {
                properties = { 'installerFlag': 'Y' };
            } else {
                properties = { 'distributorFlag': 'Y' };
            }

            //var items = $supplier.getWithProperty(properties);


            $state.go('tab.task-assigned-choice', {
                'args': {
                    'items': items,
                    'selecteds': selecteds,
                    'dbTag': dbTag
                }
            });
        };

        $dfBoradcast.getBoradcast('assignedSelected', function (data) {
            $scope.projectIntention.title = data.providerName;
            $scope.projectIntention.code = data.providerCode;
        });

        $user.getCurrentUser().executeSuccess(function (user) {
            $scope.user = user;
            projectIntention.userId = user.userId;
            $scope.projectIntention.userId = user.userId;
        });

        $scope.submitAssigned = function () {
            // $loading.show('保存项目分配.');
            var params = {
                'userId': '',
                'projectId': '',
                'distributorCode': '',
                'installerCode': ''
            };
            if ($scope.sets.haveDistri) {
                //有经销商,更新生产商
                $scope.projectIntention.installerCode = $scope.projectIntention.code;
                $scope.projectIntention.distributorCode = '';
            } else {
                //无经销商,更新经销商
                $scope.projectIntention.distributorCode = $scope.projectIntention.code;
                $scope.projectIntention.installerCode = '';
            }
            $dfHttp.post("api/project/updateProjectServiceProvider.json", $scope.projectIntention).success(function (data) {

                if (data.code == 'SUCCESS') {
                    $loading.showSuccess(data.msg);
                    if ($scope.sets.haveDistri) {
                        //有经销商,更新生产商
                        $scope.project.installerCode = $scope.projectIntention.code;
                    } else {
                        //无经销商,更新经销商
                        $scope.project.distributorCode = $scope.projectIntention.code;
                    }

                    $ionicHistory.goBack();
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (data) {
                $loading.showError("网络出了点小问题，请稍后再试");
            });
        }

        $scope.$on('$stateChangeSuccess', function () {
            //获取指定参数,如果不存在就不处理
            $lookup.clearChoiceItem();
        });
    })

    // 合同签订Ctrl
    .controller("ContractSignCtrl", function ($templateCache, $rootScope, $task, $cordovaDialogs, $scope, $stateParams, $interval, $ionicPopup, $dfUtil, $state, ionicDatePicker, $log, $user, $dfHttp, $loading, $ionicHistory, $timeout, $imageUploadCache, $cordovaFile) {
        $scope.isLoadSuccess = false;
        $scope.project = $stateParams.args.project;
        var user = $user.getCurrentUserSync();
        var imagesClass = [];

        // 调用获取合同信息方法
        getContractInfo(user.userId, $scope.project.projectId);

        /**
         * 获取合同信息
         * @param userId
         * @param projectId
         */
        function getContractInfo(userId, projectId) {
            $loading.show("正在获取合同信息");
            $dfHttp.get("api/others/getContractInfo.json", {
                userId: userId,
                projectId: projectId
                // projectId: 1000
            }).success(function (data) {
                if (data.code == "SUCCESS") {
                    $scope.isLoadSuccess = true;
                    var contractDate = data.data.contractDate;
                    data.data.contractDate = angular.isUndefined(contractDate) || contractDate == "" || contractDate === null ? $dfUtil.convertDateToString(new Date()) : contractDate;
                    data.data.projectId = projectId;
                    data.data.address = angular.isUndefined(data.data.address) || data.data.address == "" ? $scope.project.address : data.data.address;
                    data.data.contacts = angular.isUndefined(data.data.contacts) || data.data.contacts == "" ? $scope.project.contacts : data.data.contacts;
                    data.data.phone = angular.isUndefined(data.data.phone) || data.data.phone == "" ? $scope.project.contactsTel : data.data.phone;
                    data.data.amount = angular.isUndefined(data.data.amount) || data.data.amount == "" ? "" : data.data.amount;
                    $scope.contractInfo = data.data;

                    angular.forEach(data.data.classList, function (obj, index) {
                        imagesClass = obj.CONTRACT_HT;
                    });

                    $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", "CONTRACT_HT");

                    $scope.CONTRACT_HT = imagesClass.length > 0 ? "HAS_IMAGE" : "";

                    $loading.hide();
                } else {
                    $loading.showError("网络出了一点小问题,请稍后再试");
                }
            }).error(function (e) {
                $loading.showError("网络异常,请稍后再试");
            });
        }

        /**
         * 完成
         */
        $scope.save = function () {
            if ($scope.contractInfo.amount == 0) {
                $loading.showError("合同金额不可以为0");
            } else {
                if (isNull($scope.contractInfo)) {
                    $loading.showError("请填写完整，不可以为空");
                } else if ($scope.contractInfo.phone.length != 11) {
                    $loading.showError("请输入正确的手机号码");
                } else {
                    imageUpload(saveContractInfo);
                }
            }
        }

        /**
         * 提交合同信息
         * @param contractInfo
         */
        function saveContractInfo(contractInfo) {
            $loading.show("正在提交合同信息");
            $dfHttp.post("api/others/saveContractInfo.json", contractInfo).success(function (data) {
                if (data.code == "SUCCESS") {
                    $loading.showSuccess("保存合同信息成功");
                    $timeout(function () {
                        $ionicHistory.goBack();
                        $task.getCountOfTasks(user.userId);
                        $rootScope.listStatus = "ON_GOING";
                    }, 800);
                } else {
                    $loading.showError("保存合同信息失败");
                }
            }).error(function (e) {
                $loading.showError("网络异常，请稍候再试");
            })
        }

        function imageUpload(fun) {
            //$loading.showSuccess(data.msg);
            //从缓存中获取图片url,并从文件读取图片。
            if ($scope.CONTRACT_HT != "HAS_IMAGE") {
                $loading.showError("请拍照合同文件");
            } else {
                var imageCache = $imageUploadCache.getImagesByParams($scope.project.projectId, 'PROJECT', 'CONTRACT_HT');
                // var imageCache = $imageUploadCache.getImagesByParams(5621,'PROJECT','ZGPZ');
                if (!imageCache.images) {
                    imageCache.images = [];
                }

                var imageCacheCount = imageCache.images.length;
                var photoDatasArray = [];

                angular.forEach(imageCache.images, function (image) {
                    var pickImage = image.imageUrl;
                    if (image.resource == 'NETWORK') {
                        imageCacheCount--;
                        return;
                    }
                    var lastIndexOfSlash = pickImage.lastIndexOf('/');
                    var filePath = pickImage.substr(0, lastIndexOfSlash); //p
                    var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

                    $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
                        var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
                        photoDatasArray.push(base64String);
                    }, function (error) {
                        $loading.showError("本地图片没有找到,请确认存在");
                    })
                })

                $loading.show("图片提交中");
                var timer = $interval(function (e) {
                    if (photoDatasArray.length == imageCacheCount) {
                        $interval.cancel(timer);
                        $task.uploadImage("PROJECT", $scope.project.projectId, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray).success(function (data) {
                            // $task.uploadImage("PROJECT", 5621, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray).success(function (data) {
                            if (data.code == "SUCCESS") {
                                $loading.showSuccess("上传图片成功");

                                $timeout(function () {
                                    fun($scope.contractInfo);
                                }, 1000);
                            } else {
                                $loading.showError(data.msg);
                            }
                        }).error(function (error) {
                            $loading.showError("网络异常,请稍后再试");
                        })
                    } else {
                        $loading.showError("网络异常,请稍后再试");
                    }
                }, 200, 10);
            }
        }

        /**
         * 遍历查找是否有空字段
         * @param contractInfo
         * @returns {boolean}
         */
        function isNull(contractInfo) {
            var flag = false;

            if (getAttrLength(contractInfo) < 6) {
                flag = true;
            } else {
                angular.forEach(contractInfo, function (v, k) {
                    if (angular.isUndefined(v) || v == "") {
                        flag = true;
                    }
                });
            }

            return flag;
        }

        /**
         * 获取对象中属性的个数
         * @param obj
         * @returns {number}
         */
        function getAttrLength(obj) {
            var length = 0;

            for (var i in obj) {
                length++;
            }

            return length;
        }

        /**
         * 选择日期
         */
        $scope.choiceDate = function () {
            var options = {
                callback: function (val) {
                    $scope.contractInfo.contractDate = $dfUtil.convertDateToString(new Date(val));
                }
            }
            ionicDatePicker.openDatePicker(options);
        }

        /**
         * 选择图片
         * @param type
         */
        $scope.goPhoto = function (type) {
            $state.go('tab.task-common-photo', {
                "args": {
                    "funId": $scope.project.projectId,
                    "funName": "PROJECT",
                    "imageClass": type,
                    "netImages": imagesClass
                }
            });
        }

        $scope.$on("$stateChangeSuccess", function () {
            $scope.CONTRACT_HT = $imageUploadCache.getImagesCount($scope.project.projectId, "PROJECT", "CONTRACT_HT") > 0 || imagesClass.length > 0 ? "HAS_IMAGE" : "";
        })

        $scope.currencyFilter = function (amount) {
            if (typeof amount == "undefined" || amount == "") {
                $scope.contractInfo.amount = "0.00";
            } else {
                var realNumber = amount.toString();

                if (realNumber.indexOf(".") == -1) {
                    $scope.contractInfo.amount = realNumber + ".00";
                } else {
                    var integer = realNumber.substring(0, realNumber.indexOf("."));
                    var decimal = realNumber.substring(realNumber.indexOf(".") + 1);

                    if (decimal.length > 2) {
                        $scope.contractInfo.amount = integer + "." + decimal.substring(0, 2);
                    } else if (decimal.length == 1) {
                        $scope.contractInfo.amount = integer + "." + decimal + "0";
                    } else if (decimal.length == 2) {
                        $scope.contractInfo.amount = integer + "." + decimal;
                    } else {
                        $scope.contractInfo.amount = realNumber + ".00";
                    }
                }
            }

            $scope.contractInfo.amount = parseFloat($scope.contractInfo.amount);
        }

        // $scope.startConstruction = function () {
        //   imageUpload("startConstruction");
        //   // saveContractInfo($scope.contractInfo, startConstruction);
        // }

        // /**
        //  * 启动施工
        //  */
        // function startConstruction() {
        //   $timeout(function () {
        //     var popup = $ionicPopup.show({
        //       template: '<textarea id="remark" rows="5" style="overflow:hidden;resize:none;" placeholder="请填写施工备注"></textarea>',
        //       title: '合同已签订，是否确认启动施工？',
        //       buttons: [
        //         {
        //           text: '确认',
        //           type: 'button-positive',
        //           onTap: function(e) {
        //             var remark = $dfUtil.trimStr(document.getElementById("remark").value);
        //             if (remark == ""){
        //               e.preventDefault();
        //             } else {
        //               e.preventDefault();
        //               saveSetupRemark($scope.project.projectId, user.userId, remark, popup);
        //             }
        //           }
        //         },
        //         {
        //           text: '取消',
        //           type:"gray-bg",
        //           onTap:function (e) {
        //             $ionicHistory.goBack();
        //           }
        //         }
        //       ]
        //     })
        //   },1000);
        // }

        // /**
        //  * 保存施工意见
        //  * @param remark
        //  */
        // function saveSetupRemark(projectId, userId, remark, popup) {
        //   $dfHttp.post("api/others/saveSetupRemark.json",{
        //     projectId: projectId,
        //     userId: userId,
        //     setupRemark: remark
        //   }).success(function (data) {
        //     if (data.code == "SUCCESS"){
        //       $loading.showSuccess("保存施工意见成功");
        //       popup.close();
        //       $ionicHistory.goBack();
        //     } else{
        //       $loading.showError("保存失败");
        //     }
        //   }).error(function (e) {
        //     $loading.showError("网络异常，请稍候再试");
        //   });
        // }
    })

    // 方案整改Ctrl
    .controller("CorrectionCtrl", function ($rootScope, $log, $scope, $user, $task, $dfUtil, $cordovaDialogs, $cordovaFile, $state, $stateParams, $dfHttp, $loading, $imageUploadCache, $ionicHistory, $interval, $timeout) {
        var user = $user.getCurrentUserSync();
        var project = $stateParams.args.project;
        var imagesClass = [];
        $scope.spmsReform = {};

        // 获取整改
        getDesignRectification(project.projectId, user.userId);

        /**
         * 获取整改
         * @param projectId
         * @param userId
         */
        function getDesignRectification(projectId, userId) {
            $loading.show("获取数据中");
            $dfHttp.get("api/others/getDesignRectification.json", {
                projectId: projectId,
                // projectId: 5621,
                userId: userId
            }).success(function (data) {
                // $log.debug(data);
                if (data.code == "SUCCESS") {
                    $scope.spmsReform = data.data;

                    angular.forEach(data.data.classList, function (obj, index) {
                        imagesClass = obj.ZGPZ;
                    });

                    $imageUploadCache.getImagesCount(project.projectId, "PROJECT", "ZGPZ");

                    $scope.ZGPZ = imagesClass.length > 0 ? "HAS_IMAGE" : "";
                    $loading.hide();
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (e) {
                $loading.showError("网络有点小问题，请稍后再试");
            })
        }

        /**
         * 保存整改
         */
        $scope.finish = function () {
            imageUpload(saveDesignRectification);
            $rootScope.listStatus = "ON_GOING";
            $task.getCountOfTasks(user.userId);
        }

        /**
         * 保存整改
         * @param userId
         * @param spmsReform
         */
        function saveDesignRectification(spmsReform) {
            $loading.show("保存中...");
            $dfHttp.post("api/others/saveDesignRectification.json", spmsReform).success(function (data) {
                if (data.code == "SUCCESS") {
                    $loading.showSuccess(data.msg);
                    $timeout(function () {
                        $ionicHistory.goBack();
                    }, 500);
                } else {
                    $loading.showError(data.msg);
                }
            }).error(function (e) {
                $loading.showError("网络有点小问题，请稍后再试");
            });
        }

        function imageUpload(fun) {
            //$loading.showSuccess(data.msg);
            //从缓存中获取图片url,并从文件读取图片。
            if ($scope.ZGPZ != "HAS_IMAGE") {
                $loading.showError("请拍照");
            } else if (angular.isUndefined($scope.spmsReform.reformResult) || $scope.spmsReform.reformResult == "") {
                $loading.showError("请填写结论");
            } else {
                var imageCache = $imageUploadCache.getImagesByParams(project.projectId, 'PROJECT', 'ZGPZ');
                // var imageCache = $imageUploadCache.getImagesByParams(5621,'PROJECT','ZGPZ');
                if (!imageCache.images) {
                    imageCache.images = [];
                }

                var imageCacheCount = imageCache.images.length;
                var photoDatasArray = [];

                angular.forEach(imageCache.images, function (image) {
                    var pickImage = image.imageUrl;
                    if (image.resource == 'NETWORK') {
                        imageCacheCount--;
                        return;
                    }
                    var lastIndexOfSlash = pickImage.lastIndexOf('/');
                    var filePath = pickImage.substr(0, lastIndexOfSlash); //p
                    var fileName = pickImage.substr(lastIndexOfSlash + 1, pickImage.length);

                    $cordovaFile.readAsArrayBuffer(filePath, fileName).then(function (arrayBuffer) {
                        var base64String = $dfUtil.arrayBufferToBase64(arrayBuffer);
                        photoDatasArray.push(base64String);
                    }, function (error) {
                        $loading.showError("本地图片没有找到,请确认存在");
                    })
                })

                $loading.show("图片提交中");
                var timer = $interval(function (e) {
                    if (photoDatasArray.length == imageCacheCount) {
                        $interval.cancel(timer);
                        $task.uploadImage("PROJECT", project.projectId, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray).success(function (data) {
                            // $task.uploadImage("PROJECT", 5621, imageCache.imageClass, imageCache.invalidUuids, photoDatasArray).success(function (data) {
                            if (data.code == "SUCCESS") {
                                $loading.showSuccess("上传图片成功");

                                $timeout(function () {
                                    $scope.spmsReform.userId = user.userId;
                                    fun($scope.spmsReform);
                                }, 1000);
                            } else {
                                $loading.showError(data.msg);
                            }
                        }).error(function (error) {
                            $loading.showError("网络异常,请稍后再试");
                        })
                    } else {
                        $loading.showError("网络异常,请稍后再试");
                    }
                }, 200, 10);
            }
        }

        /**
         * 选择图片
         * @param type
         */
        $scope.goPhoto = function (type) {
            $state.go('tab.task-common-photo', {
                "args": {
                    "funId": project.projectId,
                    // "funId": 5621,
                    "funName": "PROJECT",
                    "imageClass": type,
                    "netImages": imagesClass
                }
            });
        }

        /**
         * 监听选择图片
         */
        $scope.$on("$stateChangeSuccess", function () {
            $scope.ZGPZ = $imageUploadCache.getImagesCount(project.projectId, "PROJECT", "ZGPZ") > 0 || imagesClass.length > 0 ? "HAS_IMAGE" : "";
        })
    })

    //并网验收
    .controller('CheckAndReceiveCtrl', function ($rootScope, $ionicHistory, $ionicActionSheet, $cordovaDialogs, $ionicPopup, $user, $region, $log, $scope, $state, $stateParams, $lookup, $task, $http, $dfHttp, $loading, $timeout, $ionicScrollDelegate, ionicDatePicker, $dfBoradcast, $dfUtil, $dfCache) {
        $log.debug($stateParams.doRefresh);
        $scope.item = $stateParams.args;

        var user = $user.getCurrentUserSync();
        // var定义的变量只能在JS里使用不能绑定到页面
        // args要寻找scope域,如果这个对象不存在就会报错
        $dfHttp.get("api/others/getAcceptanceInfo.json", { projectId: $scope.item.projectId }).success(function (data) {
            var currentDate = new Date();

            if ("SUCCESS" == data.code) {
                $scope.checkAndReceive = data.data;
                $log.debug($scope.checkAndReceive);
                if ($scope.checkAndReceive.acceptStatus == "Y") {
                    $scope.checkAndReceive.acceptStatusText = "是";
                } else {
                    $scope.checkAndReceive.acceptStatusText = "否";
                }
                if (!$scope.checkAndReceive.acceptDate || $scope.checkAndReceive.acceptDate === null) {
                    $scope.checkAndReceive.acceptDate = $dfUtil.convertDateToString(currentDate);

                }
            } else {
                $loading.showError("请求失败");
            }
        }
        ).error(function (e) {
            $loading.showError("网络异常,请稍后再试");
        });


        $scope.save = function () {
            $log.debug($scope.checkAndReceive.acceptDate);
            $dfHttp.post("api/others/saveAcceptanceInfo.json", {
                LogType: '方案审核',
                projectId: $scope.item.projectId,
                acceptDate: $scope.checkAndReceive.acceptDate,
                acceptStatus: $scope.checkAndReceive.acceptStatus,
                acceptMsg: $scope.checkAndReceive.acceptMsg
            }).success(function (data) {
                if ("SUCCESS" == data.code) {
                    $loading.showSuccess("保存成功");
                    $task.getCountOfTasks(user.userId);
                    $stateParams.doRefresh();
                    $timeout(function () {
                        $ionicHistory.goBack();
                    }, 1000)
                } else {
                    $loading.showError(data.msg);
                }

            }).error(function (e) {
                $log.debug(e);
                $loading.showError("网络异常,请稍后再试");
            });
        }
        var isNoList = [
            { text: '是', value: 'Y' },
            { text: '否', value: 'N' }
        ];
        $scope.chooseIsOrNo = function () {
            $scope.hidePoor = $ionicActionSheet.show({
                buttons: isNoList,
                //destructiveText: 'Delete',
                //titleText: 'Modify your album',
                cancelText: '取消',
                buttonClicked: function (index) {
                    $scope.checkAndReceive.acceptStatus = isNoList[index].value;
                    $scope.checkAndReceive.acceptStatusText = isNoList[index].text;
                    return true;
                }
            })
        }
        $scope.choosedate = function () {
            var currentDate = new Date();
            var options = {
                callback: function (val) {
                    $scope.checkAndReceive.acceptDate = $dfUtil.convertDateToString(new Date(val));
                },
                from: new Date(new Date().setMonth(currentDate.getMonth() - 1)),
                to: new Date(new Date().setDate(currentDate.getDate()))
            }
            ionicDatePicker.openDatePicker(options);
        }
    })
